Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67
  68    Example:
  69        >>> class Foo(Expression):
  70        ...     arg_types = {"this": True, "expression": False}
  71
  72        The above definition informs us that Foo is an Expression that requires an argument called
  73        "this" and may also optionally receive an argument called "expression".
  74
  75    Args:
  76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  77        parent: a reference to the parent expression (or None, in case of root expressions).
  78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  79            uses to refer to it.
  80        comments: a list of comments that are associated with a given expression. This is used in
  81            order to preserve comments when transpiling SQL code.
  82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  83            optimizer, in order to enable some transformations that require type information.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def append(self, arg_key, value):
 262        """
 263        Appends value to arg_key if it's a list or sets it as a new list.
 264
 265        Args:
 266            arg_key (str): name of the list expression arg
 267            value (Any): value to append to the list
 268        """
 269        if not isinstance(self.args.get(arg_key), list):
 270            self.args[arg_key] = []
 271        self.args[arg_key].append(value)
 272        self._set_parent(arg_key, value)
 273
 274    def set(self, arg_key, value):
 275        """
 276        Sets `arg_key` to `value`.
 277
 278        Args:
 279            arg_key (str): name of the expression arg.
 280            value: value to set the arg to.
 281        """
 282        self.args[arg_key] = value
 283        self._set_parent(arg_key, value)
 284
 285    def _set_parent(self, arg_key, value):
 286        if hasattr(value, "parent"):
 287            value.parent = self
 288            value.arg_key = arg_key
 289        elif type(value) is list:
 290            for v in value:
 291                if hasattr(v, "parent"):
 292                    v.parent = self
 293                    v.arg_key = arg_key
 294
 295    @property
 296    def depth(self):
 297        """
 298        Returns the depth of this tree.
 299        """
 300        if self.parent:
 301            return self.parent.depth + 1
 302        return 0
 303
 304    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 305        """Yields the key and expression for all arguments, exploding list args."""
 306        for k, vs in self.args.items():
 307            if type(vs) is list:
 308                for v in vs:
 309                    if hasattr(v, "parent"):
 310                        yield k, v
 311            else:
 312                if hasattr(vs, "parent"):
 313                    yield k, vs
 314
 315    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 316        """
 317        Returns the first node in this tree which matches at least one of
 318        the specified types.
 319
 320        Args:
 321            expression_types: the expression type(s) to match.
 322
 323        Returns:
 324            The node which matches the criteria or None if no such node was found.
 325        """
 326        return next(self.find_all(*expression_types, bfs=bfs), None)
 327
 328    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 329        """
 330        Returns a generator object which visits all nodes in this tree and only
 331        yields those that match at least one of the specified expression types.
 332
 333        Args:
 334            expression_types: the expression type(s) to match.
 335
 336        Returns:
 337            The generator object.
 338        """
 339        for expression, *_ in self.walk(bfs=bfs):
 340            if isinstance(expression, expression_types):
 341                yield expression
 342
 343    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 344        """
 345        Returns a nearest parent matching expression_types.
 346
 347        Args:
 348            expression_types: the expression type(s) to match.
 349
 350        Returns:
 351            The parent node.
 352        """
 353        ancestor = self.parent
 354        while ancestor and not isinstance(ancestor, expression_types):
 355            ancestor = ancestor.parent
 356        return t.cast(E, ancestor)
 357
 358    @property
 359    def parent_select(self):
 360        """
 361        Returns the parent select statement.
 362        """
 363        return self.find_ancestor(Select)
 364
 365    @property
 366    def same_parent(self):
 367        """Returns if the parent is the same class as itself."""
 368        return type(self.parent) is self.__class__
 369
 370    def root(self) -> Expression:
 371        """
 372        Returns the root expression of this tree.
 373        """
 374        expression = self
 375        while expression.parent:
 376            expression = expression.parent
 377        return expression
 378
 379    def walk(self, bfs=True, prune=None):
 380        """
 381        Returns a generator object which visits all nodes in this tree.
 382
 383        Args:
 384            bfs (bool): if set to True the BFS traversal order will be applied,
 385                otherwise the DFS traversal will be used instead.
 386            prune ((node, parent, arg_key) -> bool): callable that returns True if
 387                the generator should stop traversing this branch of the tree.
 388
 389        Returns:
 390            the generator object.
 391        """
 392        if bfs:
 393            yield from self.bfs(prune=prune)
 394        else:
 395            yield from self.dfs(prune=prune)
 396
 397    def dfs(self, parent=None, key=None, prune=None):
 398        """
 399        Returns a generator object which visits all nodes in this tree in
 400        the DFS (Depth-first) order.
 401
 402        Returns:
 403            The generator object.
 404        """
 405        parent = parent or self.parent
 406        yield self, parent, key
 407        if prune and prune(self, parent, key):
 408            return
 409
 410        for k, v in self.iter_expressions():
 411            yield from v.dfs(self, k, prune)
 412
 413    def bfs(self, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the BFS (Breadth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        queue = deque([(self, self.parent, None)])
 422
 423        while queue:
 424            item, parent, key = queue.popleft()
 425
 426            yield item, parent, key
 427            if prune and prune(item, parent, key):
 428                continue
 429
 430            for k, v in item.iter_expressions():
 431                queue.append((v, item, k))
 432
 433    def unnest(self):
 434        """
 435        Returns the first non parenthesis child or self.
 436        """
 437        expression = self
 438        while type(expression) is Paren:
 439            expression = expression.this
 440        return expression
 441
 442    def unalias(self):
 443        """
 444        Returns the inner expression if this is an Alias.
 445        """
 446        if isinstance(self, Alias):
 447            return self.this
 448        return self
 449
 450    def unnest_operands(self):
 451        """
 452        Returns unnested operands as a tuple.
 453        """
 454        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 455
 456    def flatten(self, unnest=True):
 457        """
 458        Returns a generator which yields child nodes who's parents are the same class.
 459
 460        A AND B AND C -> [A, B, C]
 461        """
 462        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 463            if not type(node) is self.__class__:
 464                yield node.unnest() if unnest else node
 465
 466    def __str__(self):
 467        return self.sql()
 468
 469    def __repr__(self):
 470        return self._to_s()
 471
 472    def sql(self, dialect: DialectType = None, **opts) -> str:
 473        """
 474        Returns SQL string representation of this tree.
 475
 476        Args:
 477            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 478            opts: other `sqlglot.generator.Generator` options.
 479
 480        Returns:
 481            The SQL string.
 482        """
 483        from sqlglot.dialects import Dialect
 484
 485        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 486
 487    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 488        indent = "" if not level else "\n"
 489        indent += "".join(["  "] * level)
 490        left = f"({self.key.upper()} "
 491
 492        args: t.Dict[str, t.Any] = {
 493            k: ", ".join(
 494                v._to_s(hide_missing=hide_missing, level=level + 1)
 495                if hasattr(v, "_to_s")
 496                else str(v)
 497                for v in ensure_list(vs)
 498                if v is not None
 499            )
 500            for k, vs in self.args.items()
 501        }
 502        args["comments"] = self.comments
 503        args["type"] = self.type
 504        args = {k: v for k, v in args.items() if v or not hide_missing}
 505
 506        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 507        right += ")"
 508
 509        return indent + left + right
 510
 511    def transform(self, fun, *args, copy=True, **kwargs):
 512        """
 513        Recursively visits all tree nodes (excluding already transformed ones)
 514        and applies the given transformation function to each node.
 515
 516        Args:
 517            fun (function): a function which takes a node as an argument and returns a
 518                new transformed node or the same node without modifications. If the function
 519                returns None, then the corresponding node will be removed from the syntax tree.
 520            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 521                modified in place.
 522
 523        Returns:
 524            The transformed tree.
 525        """
 526        node = self.copy() if copy else self
 527        new_node = fun(node, *args, **kwargs)
 528
 529        if new_node is None or not isinstance(new_node, Expression):
 530            return new_node
 531        if new_node is not node:
 532            new_node.parent = node.parent
 533            return new_node
 534
 535        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 536        return new_node
 537
 538    def replace(self, expression):
 539        """
 540        Swap out this expression with a new expression.
 541
 542        For example::
 543
 544            >>> tree = Select().select("x").from_("tbl")
 545            >>> tree.find(Column).replace(Column(this="y"))
 546            (COLUMN this: y)
 547            >>> tree.sql()
 548            'SELECT y FROM tbl'
 549
 550        Args:
 551            expression (Expression|None): new node
 552
 553        Returns:
 554            The new expression or expressions.
 555        """
 556        if not self.parent:
 557            return expression
 558
 559        parent = self.parent
 560        self.parent = None
 561
 562        replace_children(parent, lambda child: expression if child is self else child)
 563        return expression
 564
 565    def pop(self):
 566        """
 567        Remove this expression from its AST.
 568
 569        Returns:
 570            The popped expression.
 571        """
 572        self.replace(None)
 573        return self
 574
 575    def assert_is(self, type_):
 576        """
 577        Assert that this `Expression` is an instance of `type_`.
 578
 579        If it is NOT an instance of `type_`, this raises an assertion error.
 580        Otherwise, this returns this expression.
 581
 582        Examples:
 583            This is useful for type security in chained expressions:
 584
 585            >>> import sqlglot
 586            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 587            'SELECT x, z FROM y'
 588        """
 589        assert isinstance(self, type_)
 590        return self
 591
 592    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 593        """
 594        Checks if this expression is valid (e.g. all mandatory args are set).
 595
 596        Args:
 597            args: a sequence of values that were used to instantiate a Func expression. This is used
 598                to check that the provided arguments don't exceed the function argument limit.
 599
 600        Returns:
 601            A list of error messages for all possible errors that were found.
 602        """
 603        errors: t.List[str] = []
 604
 605        for k in self.args:
 606            if k not in self.arg_types:
 607                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 608        for k, mandatory in self.arg_types.items():
 609            v = self.args.get(k)
 610            if mandatory and (v is None or (isinstance(v, list) and not v)):
 611                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 612
 613        if (
 614            args
 615            and isinstance(self, Func)
 616            and len(args) > len(self.arg_types)
 617            and not self.is_var_len_args
 618        ):
 619            errors.append(
 620                f"The number of provided arguments ({len(args)}) is greater than "
 621                f"the maximum number of supported arguments ({len(self.arg_types)})"
 622            )
 623
 624        return errors
 625
 626    def dump(self):
 627        """
 628        Dump this Expression to a JSON-serializable dict.
 629        """
 630        from sqlglot.serde import dump
 631
 632        return dump(self)
 633
 634    @classmethod
 635    def load(cls, obj):
 636        """
 637        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 638        """
 639        from sqlglot.serde import load
 640
 641        return load(obj)
 642
 643
 644IntoType = t.Union[
 645    str,
 646    t.Type[Expression],
 647    t.Collection[t.Union[str, t.Type[Expression]]],
 648]
 649ExpOrStr = t.Union[str, Expression]
 650
 651
 652class Condition(Expression):
 653    def and_(self, *expressions, dialect=None, **opts):
 654        """
 655        AND this condition with one or multiple expressions.
 656
 657        Example:
 658            >>> condition("x=1").and_("y=1").sql()
 659            'x = 1 AND y = 1'
 660
 661        Args:
 662            *expressions (str | Expression): the SQL code strings to parse.
 663                If an `Expression` instance is passed, it will be used as-is.
 664            dialect (str): the dialect used to parse the input expression.
 665            opts (kwargs): other options to use to parse the input expressions.
 666
 667        Returns:
 668            And: the new condition.
 669        """
 670        return and_(self, *expressions, dialect=dialect, **opts)
 671
 672    def or_(self, *expressions, dialect=None, **opts):
 673        """
 674        OR this condition with one or multiple expressions.
 675
 676        Example:
 677            >>> condition("x=1").or_("y=1").sql()
 678            'x = 1 OR y = 1'
 679
 680        Args:
 681            *expressions (str | Expression): the SQL code strings to parse.
 682                If an `Expression` instance is passed, it will be used as-is.
 683            dialect (str): the dialect used to parse the input expression.
 684            opts (kwargs): other options to use to parse the input expressions.
 685
 686        Returns:
 687            Or: the new condition.
 688        """
 689        return or_(self, *expressions, dialect=dialect, **opts)
 690
 691    def not_(self):
 692        """
 693        Wrap this condition with NOT.
 694
 695        Example:
 696            >>> condition("x=1").not_().sql()
 697            'NOT x = 1'
 698
 699        Returns:
 700            Not: the new condition.
 701        """
 702        return not_(self)
 703
 704
 705class Predicate(Condition):
 706    """Relationships like x = y, x > 1, x >= y."""
 707
 708
 709class DerivedTable(Expression):
 710    @property
 711    def alias_column_names(self):
 712        table_alias = self.args.get("alias")
 713        if not table_alias:
 714            return []
 715        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 716        return [c.name for c in column_list]
 717
 718    @property
 719    def selects(self):
 720        alias = self.args.get("alias")
 721
 722        if alias:
 723            return alias.columns
 724        return []
 725
 726    @property
 727    def named_selects(self):
 728        return [select.output_name for select in self.selects]
 729
 730
 731class Unionable(Expression):
 732    def union(self, expression, distinct=True, dialect=None, **opts):
 733        """
 734        Builds a UNION expression.
 735
 736        Example:
 737            >>> import sqlglot
 738            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 739            'SELECT * FROM foo UNION SELECT * FROM bla'
 740
 741        Args:
 742            expression (str | Expression): the SQL code string.
 743                If an `Expression` instance is passed, it will be used as-is.
 744            distinct (bool): set the DISTINCT flag if and only if this is true.
 745            dialect (str): the dialect used to parse the input expression.
 746            opts (kwargs): other options to use to parse the input expressions.
 747        Returns:
 748            Union: the Union expression.
 749        """
 750        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 751
 752    def intersect(self, expression, distinct=True, dialect=None, **opts):
 753        """
 754        Builds an INTERSECT expression.
 755
 756        Example:
 757            >>> import sqlglot
 758            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 759            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 760
 761        Args:
 762            expression (str | Expression): the SQL code string.
 763                If an `Expression` instance is passed, it will be used as-is.
 764            distinct (bool): set the DISTINCT flag if and only if this is true.
 765            dialect (str): the dialect used to parse the input expression.
 766            opts (kwargs): other options to use to parse the input expressions.
 767        Returns:
 768            Intersect: the Intersect expression
 769        """
 770        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 771
 772    def except_(self, expression, distinct=True, dialect=None, **opts):
 773        """
 774        Builds an EXCEPT expression.
 775
 776        Example:
 777            >>> import sqlglot
 778            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 779            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 780
 781        Args:
 782            expression (str | Expression): the SQL code string.
 783                If an `Expression` instance is passed, it will be used as-is.
 784            distinct (bool): set the DISTINCT flag if and only if this is true.
 785            dialect (str): the dialect used to parse the input expression.
 786            opts (kwargs): other options to use to parse the input expressions.
 787        Returns:
 788            Except: the Except expression
 789        """
 790        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 791
 792
 793class UDTF(DerivedTable, Unionable):
 794    pass
 795
 796
 797class Cache(Expression):
 798    arg_types = {
 799        "with": False,
 800        "this": True,
 801        "lazy": False,
 802        "options": False,
 803        "expression": False,
 804    }
 805
 806
 807class Uncache(Expression):
 808    arg_types = {"this": True, "exists": False}
 809
 810
 811class Create(Expression):
 812    arg_types = {
 813        "with": False,
 814        "this": True,
 815        "kind": True,
 816        "expression": False,
 817        "exists": False,
 818        "properties": False,
 819        "replace": False,
 820        "unique": False,
 821        "volatile": False,
 822        "indexes": False,
 823        "no_schema_binding": False,
 824        "begin": False,
 825    }
 826
 827
 828class Describe(Expression):
 829    arg_types = {"this": True, "kind": False}
 830
 831
 832class Pragma(Expression):
 833    pass
 834
 835
 836class Set(Expression):
 837    arg_types = {"expressions": False}
 838
 839
 840class SetItem(Expression):
 841    arg_types = {
 842        "this": False,
 843        "expressions": False,
 844        "kind": False,
 845        "collate": False,  # MySQL SET NAMES statement
 846        "global": False,
 847    }
 848
 849
 850class Show(Expression):
 851    arg_types = {
 852        "this": True,
 853        "target": False,
 854        "offset": False,
 855        "limit": False,
 856        "like": False,
 857        "where": False,
 858        "db": False,
 859        "full": False,
 860        "mutex": False,
 861        "query": False,
 862        "channel": False,
 863        "global": False,
 864        "log": False,
 865        "position": False,
 866        "types": False,
 867    }
 868
 869
 870class UserDefinedFunction(Expression):
 871    arg_types = {"this": True, "expressions": False, "wrapped": False}
 872
 873
 874class CharacterSet(Expression):
 875    arg_types = {"this": True, "default": False}
 876
 877
 878class With(Expression):
 879    arg_types = {"expressions": True, "recursive": False}
 880
 881    @property
 882    def recursive(self) -> bool:
 883        return bool(self.args.get("recursive"))
 884
 885
 886class WithinGroup(Expression):
 887    arg_types = {"this": True, "expression": False}
 888
 889
 890class CTE(DerivedTable):
 891    arg_types = {"this": True, "alias": True}
 892
 893
 894class TableAlias(Expression):
 895    arg_types = {"this": False, "columns": False}
 896
 897    @property
 898    def columns(self):
 899        return self.args.get("columns") or []
 900
 901
 902class BitString(Condition):
 903    pass
 904
 905
 906class HexString(Condition):
 907    pass
 908
 909
 910class ByteString(Condition):
 911    pass
 912
 913
 914class Column(Condition):
 915    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 916
 917    @property
 918    def table(self) -> str:
 919        return self.text("table")
 920
 921    @property
 922    def db(self) -> str:
 923        return self.text("db")
 924
 925    @property
 926    def catalog(self) -> str:
 927        return self.text("catalog")
 928
 929    @property
 930    def output_name(self) -> str:
 931        return self.name
 932
 933    @property
 934    def parts(self) -> t.List[Identifier]:
 935        """Return the parts of a column in order catalog, db, table, name."""
 936        return [part for part in reversed(list(self.args.values())) if part]
 937
 938    def to_dot(self) -> Dot:
 939        """Converts the column into a dot expression."""
 940        parts = self.parts
 941        parent = self.parent
 942
 943        while parent:
 944            if isinstance(parent, Dot):
 945                parts.append(parent.expression)
 946            parent = parent.parent
 947
 948        return Dot.build(parts)
 949
 950
 951class ColumnPosition(Expression):
 952    arg_types = {"this": False, "position": True}
 953
 954
 955class ColumnDef(Expression):
 956    arg_types = {
 957        "this": True,
 958        "kind": False,
 959        "constraints": False,
 960        "exists": False,
 961        "position": False,
 962    }
 963
 964
 965class AlterColumn(Expression):
 966    arg_types = {
 967        "this": True,
 968        "dtype": False,
 969        "collate": False,
 970        "using": False,
 971        "default": False,
 972        "drop": False,
 973    }
 974
 975
 976class RenameTable(Expression):
 977    pass
 978
 979
 980class SetTag(Expression):
 981    arg_types = {"expressions": True, "unset": False}
 982
 983
 984class Comment(Expression):
 985    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 986
 987
 988class ColumnConstraint(Expression):
 989    arg_types = {"this": False, "kind": True}
 990
 991
 992class ColumnConstraintKind(Expression):
 993    pass
 994
 995
 996class AutoIncrementColumnConstraint(ColumnConstraintKind):
 997    pass
 998
 999
1000class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001    arg_types = {"not_": True}
1002
1003
1004class CharacterSetColumnConstraint(ColumnConstraintKind):
1005    arg_types = {"this": True}
1006
1007
1008class CheckColumnConstraint(ColumnConstraintKind):
1009    pass
1010
1011
1012class CollateColumnConstraint(ColumnConstraintKind):
1013    pass
1014
1015
1016class CommentColumnConstraint(ColumnConstraintKind):
1017    pass
1018
1019
1020class CompressColumnConstraint(ColumnConstraintKind):
1021    pass
1022
1023
1024class DateFormatColumnConstraint(ColumnConstraintKind):
1025    arg_types = {"this": True}
1026
1027
1028class DefaultColumnConstraint(ColumnConstraintKind):
1029    pass
1030
1031
1032class EncodeColumnConstraint(ColumnConstraintKind):
1033    pass
1034
1035
1036class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037    # this: True -> ALWAYS, this: False -> BY DEFAULT
1038    arg_types = {
1039        "this": False,
1040        "start": False,
1041        "increment": False,
1042        "minvalue": False,
1043        "maxvalue": False,
1044        "cycle": False,
1045    }
1046
1047
1048class InlineLengthColumnConstraint(ColumnConstraintKind):
1049    pass
1050
1051
1052class NotNullColumnConstraint(ColumnConstraintKind):
1053    arg_types = {"allow_null": False}
1054
1055
1056class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1057    arg_types = {"desc": False}
1058
1059
1060class TitleColumnConstraint(ColumnConstraintKind):
1061    pass
1062
1063
1064class UniqueColumnConstraint(ColumnConstraintKind):
1065    arg_types: t.Dict[str, t.Any] = {}
1066
1067
1068class UppercaseColumnConstraint(ColumnConstraintKind):
1069    arg_types: t.Dict[str, t.Any] = {}
1070
1071
1072class PathColumnConstraint(ColumnConstraintKind):
1073    pass
1074
1075
1076class Constraint(Expression):
1077    arg_types = {"this": True, "expressions": True}
1078
1079
1080class Delete(Expression):
1081    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1082
1083    def delete(
1084        self,
1085        table: ExpOrStr,
1086        dialect: DialectType = None,
1087        copy: bool = True,
1088        **opts,
1089    ) -> Delete:
1090        """
1091        Create a DELETE expression or replace the table on an existing DELETE expression.
1092
1093        Example:
1094            >>> delete("tbl").sql()
1095            'DELETE FROM tbl'
1096
1097        Args:
1098            table: the table from which to delete.
1099            dialect: the dialect used to parse the input expression.
1100            copy: if `False`, modify this expression instance in-place.
1101            opts: other options to use to parse the input expressions.
1102
1103        Returns:
1104            Delete: the modified expression.
1105        """
1106        return _apply_builder(
1107            expression=table,
1108            instance=self,
1109            arg="this",
1110            dialect=dialect,
1111            into=Table,
1112            copy=copy,
1113            **opts,
1114        )
1115
1116    def where(
1117        self,
1118        *expressions: ExpOrStr,
1119        append: bool = True,
1120        dialect: DialectType = None,
1121        copy: bool = True,
1122        **opts,
1123    ) -> Delete:
1124        """
1125        Append to or set the WHERE expressions.
1126
1127        Example:
1128            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1129            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1130
1131        Args:
1132            *expressions: the SQL code strings to parse.
1133                If an `Expression` instance is passed, it will be used as-is.
1134                Multiple expressions are combined with an AND operator.
1135            append: if `True`, AND the new expressions to any existing expression.
1136                Otherwise, this resets the expression.
1137            dialect: the dialect used to parse the input expressions.
1138            copy: if `False`, modify this expression instance in-place.
1139            opts: other options to use to parse the input expressions.
1140
1141        Returns:
1142            Delete: the modified expression.
1143        """
1144        return _apply_conjunction_builder(
1145            *expressions,
1146            instance=self,
1147            arg="where",
1148            append=append,
1149            into=Where,
1150            dialect=dialect,
1151            copy=copy,
1152            **opts,
1153        )
1154
1155    def returning(
1156        self,
1157        expression: ExpOrStr,
1158        dialect: DialectType = None,
1159        copy: bool = True,
1160        **opts,
1161    ) -> Delete:
1162        """
1163        Set the RETURNING expression. Not supported by all dialects.
1164
1165        Example:
1166            >>> delete("tbl").returning("*", dialect="postgres").sql()
1167            'DELETE FROM tbl RETURNING *'
1168
1169        Args:
1170            expression: the SQL code strings to parse.
1171                If an `Expression` instance is passed, it will be used as-is.
1172            dialect: the dialect used to parse the input expressions.
1173            copy: if `False`, modify this expression instance in-place.
1174            opts: other options to use to parse the input expressions.
1175
1176        Returns:
1177            Delete: the modified expression.
1178        """
1179        return _apply_builder(
1180            expression=expression,
1181            instance=self,
1182            arg="returning",
1183            prefix="RETURNING",
1184            dialect=dialect,
1185            copy=copy,
1186            into=Returning,
1187            **opts,
1188        )
1189
1190
1191class Drop(Expression):
1192    arg_types = {
1193        "this": False,
1194        "kind": False,
1195        "exists": False,
1196        "temporary": False,
1197        "materialized": False,
1198        "cascade": False,
1199        "constraints": False,
1200    }
1201
1202
1203class Filter(Expression):
1204    arg_types = {"this": True, "expression": True}
1205
1206
1207class Check(Expression):
1208    pass
1209
1210
1211class Directory(Expression):
1212    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1213    arg_types = {"this": True, "local": False, "row_format": False}
1214
1215
1216class ForeignKey(Expression):
1217    arg_types = {
1218        "expressions": True,
1219        "reference": False,
1220        "delete": False,
1221        "update": False,
1222    }
1223
1224
1225class PrimaryKey(Expression):
1226    arg_types = {"expressions": True, "options": False}
1227
1228
1229class Unique(Expression):
1230    arg_types = {"expressions": True}
1231
1232
1233# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1234# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1235class Into(Expression):
1236    arg_types = {"this": True, "temporary": False, "unlogged": False}
1237
1238
1239class From(Expression):
1240    arg_types = {"expressions": True}
1241
1242
1243class Having(Expression):
1244    pass
1245
1246
1247class Hint(Expression):
1248    arg_types = {"expressions": True}
1249
1250
1251class JoinHint(Expression):
1252    arg_types = {"this": True, "expressions": True}
1253
1254
1255class Identifier(Expression):
1256    arg_types = {"this": True, "quoted": False}
1257
1258    @property
1259    def quoted(self):
1260        return bool(self.args.get("quoted"))
1261
1262    @property
1263    def hashable_args(self) -> t.Any:
1264        if self.quoted and any(char.isupper() for char in self.this):
1265            return (self.this, self.quoted)
1266        return self.this.lower()
1267
1268    @property
1269    def output_name(self):
1270        return self.name
1271
1272
1273class Index(Expression):
1274    arg_types = {
1275        "this": False,
1276        "table": False,
1277        "where": False,
1278        "columns": False,
1279        "unique": False,
1280        "primary": False,
1281        "amp": False,  # teradata
1282    }
1283
1284
1285class Insert(Expression):
1286    arg_types = {
1287        "with": False,
1288        "this": True,
1289        "expression": False,
1290        "returning": False,
1291        "overwrite": False,
1292        "exists": False,
1293        "partition": False,
1294        "alternative": False,
1295    }
1296
1297
1298class Returning(Expression):
1299    arg_types = {"expressions": True}
1300
1301
1302# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1303class Introducer(Expression):
1304    arg_types = {"this": True, "expression": True}
1305
1306
1307# national char, like n'utf8'
1308class National(Expression):
1309    pass
1310
1311
1312class LoadData(Expression):
1313    arg_types = {
1314        "this": True,
1315        "local": False,
1316        "overwrite": False,
1317        "inpath": True,
1318        "partition": False,
1319        "input_format": False,
1320        "serde": False,
1321    }
1322
1323
1324class Partition(Expression):
1325    arg_types = {"expressions": True}
1326
1327
1328class Fetch(Expression):
1329    arg_types = {"direction": False, "count": False}
1330
1331
1332class Group(Expression):
1333    arg_types = {
1334        "expressions": False,
1335        "grouping_sets": False,
1336        "cube": False,
1337        "rollup": False,
1338    }
1339
1340
1341class Lambda(Expression):
1342    arg_types = {"this": True, "expressions": True}
1343
1344
1345class Limit(Expression):
1346    arg_types = {"this": False, "expression": True}
1347
1348
1349class Literal(Condition):
1350    arg_types = {"this": True, "is_string": True}
1351
1352    @property
1353    def hashable_args(self) -> t.Any:
1354        return (self.this, self.args.get("is_string"))
1355
1356    @classmethod
1357    def number(cls, number) -> Literal:
1358        return cls(this=str(number), is_string=False)
1359
1360    @classmethod
1361    def string(cls, string) -> Literal:
1362        return cls(this=str(string), is_string=True)
1363
1364    @property
1365    def output_name(self):
1366        return self.name
1367
1368
1369class Join(Expression):
1370    arg_types = {
1371        "this": True,
1372        "on": False,
1373        "side": False,
1374        "kind": False,
1375        "using": False,
1376        "natural": False,
1377    }
1378
1379    @property
1380    def kind(self):
1381        return self.text("kind").upper()
1382
1383    @property
1384    def side(self):
1385        return self.text("side").upper()
1386
1387    @property
1388    def alias_or_name(self):
1389        return self.this.alias_or_name
1390
1391    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1392        """
1393        Append to or set the ON expressions.
1394
1395        Example:
1396            >>> import sqlglot
1397            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1398            'JOIN x ON y = 1'
1399
1400        Args:
1401            *expressions (str | Expression): the SQL code strings to parse.
1402                If an `Expression` instance is passed, it will be used as-is.
1403                Multiple expressions are combined with an AND operator.
1404            append (bool): if `True`, AND the new expressions to any existing expression.
1405                Otherwise, this resets the expression.
1406            dialect (str): the dialect used to parse the input expressions.
1407            copy (bool): if `False`, modify this expression instance in-place.
1408            opts (kwargs): other options to use to parse the input expressions.
1409
1410        Returns:
1411            Join: the modified join expression.
1412        """
1413        join = _apply_conjunction_builder(
1414            *expressions,
1415            instance=self,
1416            arg="on",
1417            append=append,
1418            dialect=dialect,
1419            copy=copy,
1420            **opts,
1421        )
1422
1423        if join.kind == "CROSS":
1424            join.set("kind", None)
1425
1426        return join
1427
1428    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1429        """
1430        Append to or set the USING expressions.
1431
1432        Example:
1433            >>> import sqlglot
1434            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1435            'JOIN x USING (foo, bla)'
1436
1437        Args:
1438            *expressions (str | Expression): the SQL code strings to parse.
1439                If an `Expression` instance is passed, it will be used as-is.
1440            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1441                Otherwise, this resets the expression.
1442            dialect (str): the dialect used to parse the input expressions.
1443            copy (bool): if `False`, modify this expression instance in-place.
1444            opts (kwargs): other options to use to parse the input expressions.
1445
1446        Returns:
1447            Join: the modified join expression.
1448        """
1449        join = _apply_list_builder(
1450            *expressions,
1451            instance=self,
1452            arg="using",
1453            append=append,
1454            dialect=dialect,
1455            copy=copy,
1456            **opts,
1457        )
1458
1459        if join.kind == "CROSS":
1460            join.set("kind", None)
1461
1462        return join
1463
1464
1465class Lateral(UDTF):
1466    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1467
1468
1469class MatchRecognize(Expression):
1470    arg_types = {
1471        "partition_by": False,
1472        "order": False,
1473        "measures": False,
1474        "rows": False,
1475        "after": False,
1476        "pattern": False,
1477        "define": False,
1478    }
1479
1480
1481# Clickhouse FROM FINAL modifier
1482# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1483class Final(Expression):
1484    pass
1485
1486
1487class Offset(Expression):
1488    arg_types = {"this": False, "expression": True}
1489
1490
1491class Order(Expression):
1492    arg_types = {"this": False, "expressions": True}
1493
1494
1495# hive specific sorts
1496# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1497class Cluster(Order):
1498    pass
1499
1500
1501class Distribute(Order):
1502    pass
1503
1504
1505class Sort(Order):
1506    pass
1507
1508
1509class Ordered(Expression):
1510    arg_types = {"this": True, "desc": True, "nulls_first": True}
1511
1512
1513class Property(Expression):
1514    arg_types = {"this": True, "value": True}
1515
1516
1517class AfterJournalProperty(Property):
1518    arg_types = {"no": True, "dual": False, "local": False}
1519
1520
1521class AlgorithmProperty(Property):
1522    arg_types = {"this": True}
1523
1524
1525class AutoIncrementProperty(Property):
1526    arg_types = {"this": True}
1527
1528
1529class BlockCompressionProperty(Property):
1530    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1531
1532
1533class CharacterSetProperty(Property):
1534    arg_types = {"this": True, "default": True}
1535
1536
1537class ChecksumProperty(Property):
1538    arg_types = {"on": False, "default": False}
1539
1540
1541class CollateProperty(Property):
1542    arg_types = {"this": True}
1543
1544
1545class DataBlocksizeProperty(Property):
1546    arg_types = {"size": False, "units": False, "min": False, "default": False}
1547
1548
1549class DefinerProperty(Property):
1550    arg_types = {"this": True}
1551
1552
1553class DistKeyProperty(Property):
1554    arg_types = {"this": True}
1555
1556
1557class DistStyleProperty(Property):
1558    arg_types = {"this": True}
1559
1560
1561class EngineProperty(Property):
1562    arg_types = {"this": True}
1563
1564
1565class ExecuteAsProperty(Property):
1566    arg_types = {"this": True}
1567
1568
1569class ExternalProperty(Property):
1570    arg_types = {"this": False}
1571
1572
1573class FallbackProperty(Property):
1574    arg_types = {"no": True, "protection": False}
1575
1576
1577class FileFormatProperty(Property):
1578    arg_types = {"this": True}
1579
1580
1581class FreespaceProperty(Property):
1582    arg_types = {"this": True, "percent": False}
1583
1584
1585class IsolatedLoadingProperty(Property):
1586    arg_types = {
1587        "no": True,
1588        "concurrent": True,
1589        "for_all": True,
1590        "for_insert": True,
1591        "for_none": True,
1592    }
1593
1594
1595class JournalProperty(Property):
1596    arg_types = {"no": True, "dual": False, "before": False}
1597
1598
1599class LanguageProperty(Property):
1600    arg_types = {"this": True}
1601
1602
1603class LikeProperty(Property):
1604    arg_types = {"this": True, "expressions": False}
1605
1606
1607class LocationProperty(Property):
1608    arg_types = {"this": True}
1609
1610
1611class LockingProperty(Property):
1612    arg_types = {
1613        "this": False,
1614        "kind": True,
1615        "for_or_in": True,
1616        "lock_type": True,
1617        "override": False,
1618    }
1619
1620
1621class LogProperty(Property):
1622    arg_types = {"no": True}
1623
1624
1625class MaterializedProperty(Property):
1626    arg_types = {"this": False}
1627
1628
1629class MergeBlockRatioProperty(Property):
1630    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1631
1632
1633class NoPrimaryIndexProperty(Property):
1634    arg_types = {"this": False}
1635
1636
1637class OnCommitProperty(Property):
1638    arg_type = {"this": False}
1639
1640
1641class PartitionedByProperty(Property):
1642    arg_types = {"this": True}
1643
1644
1645class ReturnsProperty(Property):
1646    arg_types = {"this": True, "is_table": False, "table": False}
1647
1648
1649class RowFormatDelimitedProperty(Property):
1650    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1651    arg_types = {
1652        "fields": False,
1653        "escaped": False,
1654        "collection_items": False,
1655        "map_keys": False,
1656        "lines": False,
1657        "null": False,
1658        "serde": False,
1659    }
1660
1661
1662class RowFormatSerdeProperty(Property):
1663    arg_types = {"this": True}
1664
1665
1666class SchemaCommentProperty(Property):
1667    arg_types = {"this": True}
1668
1669
1670class SerdeProperties(Property):
1671    arg_types = {"expressions": True}
1672
1673
1674class SetProperty(Property):
1675    arg_types = {"multi": True}
1676
1677
1678class SortKeyProperty(Property):
1679    arg_types = {"this": True, "compound": False}
1680
1681
1682class SqlSecurityProperty(Property):
1683    arg_types = {"definer": True}
1684
1685
1686class TableFormatProperty(Property):
1687    arg_types = {"this": True}
1688
1689
1690class TemporaryProperty(Property):
1691    arg_types = {"global_": True}
1692
1693
1694class TransientProperty(Property):
1695    arg_types = {"this": False}
1696
1697
1698class VolatilityProperty(Property):
1699    arg_types = {"this": True}
1700
1701
1702class WithDataProperty(Property):
1703    arg_types = {"no": True, "statistics": False}
1704
1705
1706class WithJournalTableProperty(Property):
1707    arg_types = {"this": True}
1708
1709
1710class Properties(Expression):
1711    arg_types = {"expressions": True}
1712
1713    NAME_TO_PROPERTY = {
1714        "ALGORITHM": AlgorithmProperty,
1715        "AUTO_INCREMENT": AutoIncrementProperty,
1716        "CHARACTER SET": CharacterSetProperty,
1717        "COLLATE": CollateProperty,
1718        "COMMENT": SchemaCommentProperty,
1719        "DEFINER": DefinerProperty,
1720        "DISTKEY": DistKeyProperty,
1721        "DISTSTYLE": DistStyleProperty,
1722        "ENGINE": EngineProperty,
1723        "EXECUTE AS": ExecuteAsProperty,
1724        "FORMAT": FileFormatProperty,
1725        "LANGUAGE": LanguageProperty,
1726        "LOCATION": LocationProperty,
1727        "PARTITIONED_BY": PartitionedByProperty,
1728        "RETURNS": ReturnsProperty,
1729        "SORTKEY": SortKeyProperty,
1730        "TABLE_FORMAT": TableFormatProperty,
1731    }
1732
1733    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1734
1735    # CREATE property locations
1736    # Form: schema specified
1737    #   create [POST_CREATE]
1738    #     table a [POST_NAME]
1739    #     (b int) [POST_SCHEMA]
1740    #     with ([POST_WITH])
1741    #     index (b) [POST_INDEX]
1742    #
1743    # Form: alias selection
1744    #   create [POST_CREATE]
1745    #     table a [POST_NAME]
1746    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1747    #     index (c) [POST_INDEX]
1748    class Location(AutoName):
1749        POST_CREATE = auto()
1750        POST_NAME = auto()
1751        POST_SCHEMA = auto()
1752        POST_WITH = auto()
1753        POST_ALIAS = auto()
1754        POST_EXPRESSION = auto()
1755        POST_INDEX = auto()
1756        UNSUPPORTED = auto()
1757
1758    @classmethod
1759    def from_dict(cls, properties_dict) -> Properties:
1760        expressions = []
1761        for key, value in properties_dict.items():
1762            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1763            if property_cls:
1764                expressions.append(property_cls(this=convert(value)))
1765            else:
1766                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1767
1768        return cls(expressions=expressions)
1769
1770
1771class Qualify(Expression):
1772    pass
1773
1774
1775# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1776class Return(Expression):
1777    pass
1778
1779
1780class Reference(Expression):
1781    arg_types = {"this": True, "expressions": False, "options": False}
1782
1783
1784class Tuple(Expression):
1785    arg_types = {"expressions": False}
1786
1787
1788class Subqueryable(Unionable):
1789    def subquery(self, alias=None, copy=True) -> Subquery:
1790        """
1791        Convert this expression to an aliased expression that can be used as a Subquery.
1792
1793        Example:
1794            >>> subquery = Select().select("x").from_("tbl").subquery()
1795            >>> Select().select("x").from_(subquery).sql()
1796            'SELECT x FROM (SELECT x FROM tbl)'
1797
1798        Args:
1799            alias (str | Identifier): an optional alias for the subquery
1800            copy (bool): if `False`, modify this expression instance in-place.
1801
1802        Returns:
1803            Alias: the subquery
1804        """
1805        instance = _maybe_copy(self, copy)
1806        return Subquery(
1807            this=instance,
1808            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1809        )
1810
1811    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1812        raise NotImplementedError
1813
1814    @property
1815    def ctes(self):
1816        with_ = self.args.get("with")
1817        if not with_:
1818            return []
1819        return with_.expressions
1820
1821    @property
1822    def selects(self):
1823        raise NotImplementedError("Subqueryable objects must implement `selects`")
1824
1825    @property
1826    def named_selects(self):
1827        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1828
1829    def with_(
1830        self,
1831        alias,
1832        as_,
1833        recursive=None,
1834        append=True,
1835        dialect=None,
1836        copy=True,
1837        **opts,
1838    ):
1839        """
1840        Append to or set the common table expressions.
1841
1842        Example:
1843            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1844            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1845
1846        Args:
1847            alias (str | Expression): the SQL code string to parse as the table name.
1848                If an `Expression` instance is passed, this is used as-is.
1849            as_ (str | Expression): the SQL code string to parse as the table expression.
1850                If an `Expression` instance is passed, it will be used as-is.
1851            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1852            append (bool): if `True`, add to any existing expressions.
1853                Otherwise, this resets the expressions.
1854            dialect (str): the dialect used to parse the input expression.
1855            copy (bool): if `False`, modify this expression instance in-place.
1856            opts (kwargs): other options to use to parse the input expressions.
1857
1858        Returns:
1859            Select: the modified expression.
1860        """
1861        alias_expression = maybe_parse(
1862            alias,
1863            dialect=dialect,
1864            into=TableAlias,
1865            **opts,
1866        )
1867        as_expression = maybe_parse(
1868            as_,
1869            dialect=dialect,
1870            **opts,
1871        )
1872        cte = CTE(
1873            this=as_expression,
1874            alias=alias_expression,
1875        )
1876        return _apply_child_list_builder(
1877            cte,
1878            instance=self,
1879            arg="with",
1880            append=append,
1881            copy=copy,
1882            into=With,
1883            properties={"recursive": recursive or False},
1884        )
1885
1886
1887QUERY_MODIFIERS = {
1888    "match": False,
1889    "laterals": False,
1890    "joins": False,
1891    "pivots": False,
1892    "where": False,
1893    "group": False,
1894    "having": False,
1895    "qualify": False,
1896    "windows": False,
1897    "distribute": False,
1898    "sort": False,
1899    "cluster": False,
1900    "order": False,
1901    "limit": False,
1902    "offset": False,
1903    "lock": False,
1904    "sample": False,
1905}
1906
1907
1908class Table(Expression):
1909    arg_types = {
1910        "this": True,
1911        "alias": False,
1912        "db": False,
1913        "catalog": False,
1914        "laterals": False,
1915        "joins": False,
1916        "pivots": False,
1917        "hints": False,
1918        "system_time": False,
1919    }
1920
1921    @property
1922    def db(self) -> str:
1923        return self.text("db")
1924
1925    @property
1926    def catalog(self) -> str:
1927        return self.text("catalog")
1928
1929
1930# See the TSQL "Querying data in a system-versioned temporal table" page
1931class SystemTime(Expression):
1932    arg_types = {
1933        "this": False,
1934        "expression": False,
1935        "kind": True,
1936    }
1937
1938
1939class Union(Subqueryable):
1940    arg_types = {
1941        "with": False,
1942        "this": True,
1943        "expression": True,
1944        "distinct": False,
1945        **QUERY_MODIFIERS,
1946    }
1947
1948    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1949        """
1950        Set the LIMIT expression.
1951
1952        Example:
1953            >>> select("1").union(select("1")).limit(1).sql()
1954            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1955
1956        Args:
1957            expression (str | int | Expression): the SQL code string to parse.
1958                This can also be an integer.
1959                If a `Limit` instance is passed, this is used as-is.
1960                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1961            dialect (str): the dialect used to parse the input expression.
1962            copy (bool): if `False`, modify this expression instance in-place.
1963            opts (kwargs): other options to use to parse the input expressions.
1964
1965        Returns:
1966            Select: The limited subqueryable.
1967        """
1968        return (
1969            select("*")
1970            .from_(self.subquery(alias="_l_0", copy=copy))
1971            .limit(expression, dialect=dialect, copy=False, **opts)
1972        )
1973
1974    def select(
1975        self,
1976        *expressions: ExpOrStr,
1977        append: bool = True,
1978        dialect: DialectType = None,
1979        copy: bool = True,
1980        **opts,
1981    ) -> Union:
1982        """Append to or set the SELECT of the union recursively.
1983
1984        Example:
1985            >>> from sqlglot import parse_one
1986            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1987            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1988
1989        Args:
1990            *expressions: the SQL code strings to parse.
1991                If an `Expression` instance is passed, it will be used as-is.
1992            append: if `True`, add to any existing expressions.
1993                Otherwise, this resets the expressions.
1994            dialect: the dialect used to parse the input expressions.
1995            copy: if `False`, modify this expression instance in-place.
1996            opts: other options to use to parse the input expressions.
1997
1998        Returns:
1999            Union: the modified expression.
2000        """
2001        this = self.copy() if copy else self
2002        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2003        this.expression.unnest().select(
2004            *expressions, append=append, dialect=dialect, copy=False, **opts
2005        )
2006        return this
2007
2008    @property
2009    def named_selects(self):
2010        return self.this.unnest().named_selects
2011
2012    @property
2013    def is_star(self) -> bool:
2014        return self.this.is_star or self.expression.is_star
2015
2016    @property
2017    def selects(self):
2018        return self.this.unnest().selects
2019
2020    @property
2021    def left(self):
2022        return self.this
2023
2024    @property
2025    def right(self):
2026        return self.expression
2027
2028
2029class Except(Union):
2030    pass
2031
2032
2033class Intersect(Union):
2034    pass
2035
2036
2037class Unnest(UDTF):
2038    arg_types = {
2039        "expressions": True,
2040        "ordinality": False,
2041        "alias": False,
2042        "offset": False,
2043    }
2044
2045
2046class Update(Expression):
2047    arg_types = {
2048        "with": False,
2049        "this": False,
2050        "expressions": True,
2051        "from": False,
2052        "where": False,
2053        "returning": False,
2054    }
2055
2056
2057class Values(UDTF):
2058    arg_types = {
2059        "expressions": True,
2060        "ordinality": False,
2061        "alias": False,
2062    }
2063
2064
2065class Var(Expression):
2066    pass
2067
2068
2069class Schema(Expression):
2070    arg_types = {"this": False, "expressions": False}
2071
2072
2073# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2074# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2075class Lock(Expression):
2076    arg_types = {"update": True}
2077
2078
2079class Select(Subqueryable):
2080    arg_types = {
2081        "with": False,
2082        "kind": False,
2083        "expressions": False,
2084        "hint": False,
2085        "distinct": False,
2086        "into": False,
2087        "from": False,
2088        **QUERY_MODIFIERS,
2089    }
2090
2091    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2092        """
2093        Set the FROM expression.
2094
2095        Example:
2096            >>> Select().from_("tbl").select("x").sql()
2097            'SELECT x FROM tbl'
2098
2099        Args:
2100            *expressions (str | Expression): the SQL code strings to parse.
2101                If a `From` instance is passed, this is used as-is.
2102                If another `Expression` instance is passed, it will be wrapped in a `From`.
2103            append (bool): if `True`, add to any existing expressions.
2104                Otherwise, this flattens all the `From` expression into a single expression.
2105            dialect (str): the dialect used to parse the input expression.
2106            copy (bool): if `False`, modify this expression instance in-place.
2107            opts (kwargs): other options to use to parse the input expressions.
2108
2109        Returns:
2110            Select: the modified expression.
2111        """
2112        return _apply_child_list_builder(
2113            *expressions,
2114            instance=self,
2115            arg="from",
2116            append=append,
2117            copy=copy,
2118            prefix="FROM",
2119            into=From,
2120            dialect=dialect,
2121            **opts,
2122        )
2123
2124    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2125        """
2126        Set the GROUP BY expression.
2127
2128        Example:
2129            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2130            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2131
2132        Args:
2133            *expressions (str | Expression): the SQL code strings to parse.
2134                If a `Group` instance is passed, this is used as-is.
2135                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2136                If nothing is passed in then a group by is not applied to the expression
2137            append (bool): if `True`, add to any existing expressions.
2138                Otherwise, this flattens all the `Group` expression into a single expression.
2139            dialect (str): the dialect used to parse the input expression.
2140            copy (bool): if `False`, modify this expression instance in-place.
2141            opts (kwargs): other options to use to parse the input expressions.
2142
2143        Returns:
2144            Select: the modified expression.
2145        """
2146        if not expressions:
2147            return self if not copy else self.copy()
2148        return _apply_child_list_builder(
2149            *expressions,
2150            instance=self,
2151            arg="group",
2152            append=append,
2153            copy=copy,
2154            prefix="GROUP BY",
2155            into=Group,
2156            dialect=dialect,
2157            **opts,
2158        )
2159
2160    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2161        """
2162        Set the ORDER BY expression.
2163
2164        Example:
2165            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2166            'SELECT x FROM tbl ORDER BY x DESC'
2167
2168        Args:
2169            *expressions (str | Expression): the SQL code strings to parse.
2170                If a `Group` instance is passed, this is used as-is.
2171                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2172            append (bool): if `True`, add to any existing expressions.
2173                Otherwise, this flattens all the `Order` expression into a single expression.
2174            dialect (str): the dialect used to parse the input expression.
2175            copy (bool): if `False`, modify this expression instance in-place.
2176            opts (kwargs): other options to use to parse the input expressions.
2177
2178        Returns:
2179            Select: the modified expression.
2180        """
2181        return _apply_child_list_builder(
2182            *expressions,
2183            instance=self,
2184            arg="order",
2185            append=append,
2186            copy=copy,
2187            prefix="ORDER BY",
2188            into=Order,
2189            dialect=dialect,
2190            **opts,
2191        )
2192
2193    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2194        """
2195        Set the SORT BY expression.
2196
2197        Example:
2198            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2199            'SELECT x FROM tbl SORT BY x DESC'
2200
2201        Args:
2202            *expressions (str | Expression): the SQL code strings to parse.
2203                If a `Group` instance is passed, this is used as-is.
2204                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2205            append (bool): if `True`, add to any existing expressions.
2206                Otherwise, this flattens all the `Order` expression into a single expression.
2207            dialect (str): the dialect used to parse the input expression.
2208            copy (bool): if `False`, modify this expression instance in-place.
2209            opts (kwargs): other options to use to parse the input expressions.
2210
2211        Returns:
2212            Select: the modified expression.
2213        """
2214        return _apply_child_list_builder(
2215            *expressions,
2216            instance=self,
2217            arg="sort",
2218            append=append,
2219            copy=copy,
2220            prefix="SORT BY",
2221            into=Sort,
2222            dialect=dialect,
2223            **opts,
2224        )
2225
2226    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2227        """
2228        Set the CLUSTER BY expression.
2229
2230        Example:
2231            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2232            'SELECT x FROM tbl CLUSTER BY x DESC'
2233
2234        Args:
2235            *expressions (str | Expression): the SQL code strings to parse.
2236                If a `Group` instance is passed, this is used as-is.
2237                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2238            append (bool): if `True`, add to any existing expressions.
2239                Otherwise, this flattens all the `Order` expression into a single expression.
2240            dialect (str): the dialect used to parse the input expression.
2241            copy (bool): if `False`, modify this expression instance in-place.
2242            opts (kwargs): other options to use to parse the input expressions.
2243
2244        Returns:
2245            Select: the modified expression.
2246        """
2247        return _apply_child_list_builder(
2248            *expressions,
2249            instance=self,
2250            arg="cluster",
2251            append=append,
2252            copy=copy,
2253            prefix="CLUSTER BY",
2254            into=Cluster,
2255            dialect=dialect,
2256            **opts,
2257        )
2258
2259    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2260        """
2261        Set the LIMIT expression.
2262
2263        Example:
2264            >>> Select().from_("tbl").select("x").limit(10).sql()
2265            'SELECT x FROM tbl LIMIT 10'
2266
2267        Args:
2268            expression (str | int | Expression): the SQL code string to parse.
2269                This can also be an integer.
2270                If a `Limit` instance is passed, this is used as-is.
2271                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2272            dialect (str): the dialect used to parse the input expression.
2273            copy (bool): if `False`, modify this expression instance in-place.
2274            opts (kwargs): other options to use to parse the input expressions.
2275
2276        Returns:
2277            Select: the modified expression.
2278        """
2279        return _apply_builder(
2280            expression=expression,
2281            instance=self,
2282            arg="limit",
2283            into=Limit,
2284            prefix="LIMIT",
2285            dialect=dialect,
2286            copy=copy,
2287            **opts,
2288        )
2289
2290    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2291        """
2292        Set the OFFSET expression.
2293
2294        Example:
2295            >>> Select().from_("tbl").select("x").offset(10).sql()
2296            'SELECT x FROM tbl OFFSET 10'
2297
2298        Args:
2299            expression (str | int | Expression): the SQL code string to parse.
2300                This can also be an integer.
2301                If a `Offset` instance is passed, this is used as-is.
2302                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2303            dialect (str): the dialect used to parse the input expression.
2304            copy (bool): if `False`, modify this expression instance in-place.
2305            opts (kwargs): other options to use to parse the input expressions.
2306
2307        Returns:
2308            Select: the modified expression.
2309        """
2310        return _apply_builder(
2311            expression=expression,
2312            instance=self,
2313            arg="offset",
2314            into=Offset,
2315            prefix="OFFSET",
2316            dialect=dialect,
2317            copy=copy,
2318            **opts,
2319        )
2320
2321    def select(
2322        self,
2323        *expressions: ExpOrStr,
2324        append: bool = True,
2325        dialect: DialectType = None,
2326        copy: bool = True,
2327        **opts,
2328    ) -> Select:
2329        """
2330        Append to or set the SELECT expressions.
2331
2332        Example:
2333            >>> Select().select("x", "y").sql()
2334            'SELECT x, y'
2335
2336        Args:
2337            *expressions: the SQL code strings to parse.
2338                If an `Expression` instance is passed, it will be used as-is.
2339            append: if `True`, add to any existing expressions.
2340                Otherwise, this resets the expressions.
2341            dialect: the dialect used to parse the input expressions.
2342            copy: if `False`, modify this expression instance in-place.
2343            opts: other options to use to parse the input expressions.
2344
2345        Returns:
2346            Select: the modified expression.
2347        """
2348        return _apply_list_builder(
2349            *expressions,
2350            instance=self,
2351            arg="expressions",
2352            append=append,
2353            dialect=dialect,
2354            copy=copy,
2355            **opts,
2356        )
2357
2358    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2359        """
2360        Append to or set the LATERAL expressions.
2361
2362        Example:
2363            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2364            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2365
2366        Args:
2367            *expressions (str | Expression): the SQL code strings to parse.
2368                If an `Expression` instance is passed, it will be used as-is.
2369            append (bool): if `True`, add to any existing expressions.
2370                Otherwise, this resets the expressions.
2371            dialect (str): the dialect used to parse the input expressions.
2372            copy (bool): if `False`, modify this expression instance in-place.
2373            opts (kwargs): other options to use to parse the input expressions.
2374
2375        Returns:
2376            Select: the modified expression.
2377        """
2378        return _apply_list_builder(
2379            *expressions,
2380            instance=self,
2381            arg="laterals",
2382            append=append,
2383            into=Lateral,
2384            prefix="LATERAL VIEW",
2385            dialect=dialect,
2386            copy=copy,
2387            **opts,
2388        )
2389
2390    def join(
2391        self,
2392        expression,
2393        on=None,
2394        using=None,
2395        append=True,
2396        join_type=None,
2397        join_alias=None,
2398        dialect=None,
2399        copy=True,
2400        **opts,
2401    ) -> Select:
2402        """
2403        Append to or set the JOIN expressions.
2404
2405        Example:
2406            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2407            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2408
2409            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2410            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2411
2412            Use `join_type` to change the type of join:
2413
2414            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2415            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2416
2417        Args:
2418            expression (str | Expression): the SQL code string to parse.
2419                If an `Expression` instance is passed, it will be used as-is.
2420            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2421                If an `Expression` instance is passed, it will be used as-is.
2422            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2423                If an `Expression` instance is passed, it will be used as-is.
2424            append (bool): if `True`, add to any existing expressions.
2425                Otherwise, this resets the expressions.
2426            join_type (str): If set, alter the parsed join type
2427            dialect (str): the dialect used to parse the input expressions.
2428            copy (bool): if `False`, modify this expression instance in-place.
2429            opts (kwargs): other options to use to parse the input expressions.
2430
2431        Returns:
2432            Select: the modified expression.
2433        """
2434        parse_args = {"dialect": dialect, **opts}
2435
2436        try:
2437            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2438        except ParseError:
2439            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2440
2441        join = expression if isinstance(expression, Join) else Join(this=expression)
2442
2443        if isinstance(join.this, Select):
2444            join.this.replace(join.this.subquery())
2445
2446        if join_type:
2447            natural: t.Optional[Token]
2448            side: t.Optional[Token]
2449            kind: t.Optional[Token]
2450
2451            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2452
2453            if natural:
2454                join.set("natural", True)
2455            if side:
2456                join.set("side", side.text)
2457            if kind:
2458                join.set("kind", kind.text)
2459
2460        if on:
2461            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2462            join.set("on", on)
2463
2464        if using:
2465            join = _apply_list_builder(
2466                *ensure_collection(using),
2467                instance=join,
2468                arg="using",
2469                append=append,
2470                copy=copy,
2471                **opts,
2472            )
2473
2474        if join_alias:
2475            join.set("this", alias_(join.this, join_alias, table=True))
2476        return _apply_list_builder(
2477            join,
2478            instance=self,
2479            arg="joins",
2480            append=append,
2481            copy=copy,
2482            **opts,
2483        )
2484
2485    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2486        """
2487        Append to or set the WHERE expressions.
2488
2489        Example:
2490            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2491            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2492
2493        Args:
2494            *expressions (str | Expression): the SQL code strings to parse.
2495                If an `Expression` instance is passed, it will be used as-is.
2496                Multiple expressions are combined with an AND operator.
2497            append (bool): if `True`, AND the new expressions to any existing expression.
2498                Otherwise, this resets the expression.
2499            dialect (str): the dialect used to parse the input expressions.
2500            copy (bool): if `False`, modify this expression instance in-place.
2501            opts (kwargs): other options to use to parse the input expressions.
2502
2503        Returns:
2504            Select: the modified expression.
2505        """
2506        return _apply_conjunction_builder(
2507            *expressions,
2508            instance=self,
2509            arg="where",
2510            append=append,
2511            into=Where,
2512            dialect=dialect,
2513            copy=copy,
2514            **opts,
2515        )
2516
2517    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2518        """
2519        Append to or set the HAVING expressions.
2520
2521        Example:
2522            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2523            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2524
2525        Args:
2526            *expressions (str | Expression): the SQL code strings to parse.
2527                If an `Expression` instance is passed, it will be used as-is.
2528                Multiple expressions are combined with an AND operator.
2529            append (bool): if `True`, AND the new expressions to any existing expression.
2530                Otherwise, this resets the expression.
2531            dialect (str): the dialect used to parse the input expressions.
2532            copy (bool): if `False`, modify this expression instance in-place.
2533            opts (kwargs): other options to use to parse the input expressions.
2534
2535        Returns:
2536            Select: the modified expression.
2537        """
2538        return _apply_conjunction_builder(
2539            *expressions,
2540            instance=self,
2541            arg="having",
2542            append=append,
2543            into=Having,
2544            dialect=dialect,
2545            copy=copy,
2546            **opts,
2547        )
2548
2549    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2550        return _apply_list_builder(
2551            *expressions,
2552            instance=self,
2553            arg="windows",
2554            append=append,
2555            into=Window,
2556            dialect=dialect,
2557            copy=copy,
2558            **opts,
2559        )
2560
2561    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2562        return _apply_conjunction_builder(
2563            *expressions,
2564            instance=self,
2565            arg="qualify",
2566            append=append,
2567            into=Qualify,
2568            dialect=dialect,
2569            copy=copy,
2570            **opts,
2571        )
2572
2573    def distinct(self, distinct=True, copy=True) -> Select:
2574        """
2575        Set the OFFSET expression.
2576
2577        Example:
2578            >>> Select().from_("tbl").select("x").distinct().sql()
2579            'SELECT DISTINCT x FROM tbl'
2580
2581        Args:
2582            distinct (bool): whether the Select should be distinct
2583            copy (bool): if `False`, modify this expression instance in-place.
2584
2585        Returns:
2586            Select: the modified expression.
2587        """
2588        instance = _maybe_copy(self, copy)
2589        instance.set("distinct", Distinct() if distinct else None)
2590        return instance
2591
2592    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2593        """
2594        Convert this expression to a CREATE TABLE AS statement.
2595
2596        Example:
2597            >>> Select().select("*").from_("tbl").ctas("x").sql()
2598            'CREATE TABLE x AS SELECT * FROM tbl'
2599
2600        Args:
2601            table (str | Expression): the SQL code string to parse as the table name.
2602                If another `Expression` instance is passed, it will be used as-is.
2603            properties (dict): an optional mapping of table properties
2604            dialect (str): the dialect used to parse the input table.
2605            copy (bool): if `False`, modify this expression instance in-place.
2606            opts (kwargs): other options to use to parse the input table.
2607
2608        Returns:
2609            Create: the CREATE TABLE AS expression
2610        """
2611        instance = _maybe_copy(self, copy)
2612        table_expression = maybe_parse(
2613            table,
2614            into=Table,
2615            dialect=dialect,
2616            **opts,
2617        )
2618        properties_expression = None
2619        if properties:
2620            properties_expression = Properties.from_dict(properties)
2621
2622        return Create(
2623            this=table_expression,
2624            kind="table",
2625            expression=instance,
2626            properties=properties_expression,
2627        )
2628
2629    def lock(self, update: bool = True, copy: bool = True) -> Select:
2630        """
2631        Set the locking read mode for this expression.
2632
2633        Examples:
2634            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2635            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2636
2637            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2638            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2639
2640        Args:
2641            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2642            copy: if `False`, modify this expression instance in-place.
2643
2644        Returns:
2645            The modified expression.
2646        """
2647
2648        inst = _maybe_copy(self, copy)
2649        inst.set("lock", Lock(update=update))
2650
2651        return inst
2652
2653    @property
2654    def named_selects(self) -> t.List[str]:
2655        return [e.output_name for e in self.expressions if e.alias_or_name]
2656
2657    @property
2658    def is_star(self) -> bool:
2659        return any(expression.is_star for expression in self.expressions)
2660
2661    @property
2662    def selects(self) -> t.List[Expression]:
2663        return self.expressions
2664
2665
2666class Subquery(DerivedTable, Unionable):
2667    arg_types = {
2668        "this": True,
2669        "alias": False,
2670        "with": False,
2671        **QUERY_MODIFIERS,
2672    }
2673
2674    def unnest(self):
2675        """
2676        Returns the first non subquery.
2677        """
2678        expression = self
2679        while isinstance(expression, Subquery):
2680            expression = expression.this
2681        return expression
2682
2683    @property
2684    def is_star(self) -> bool:
2685        return self.this.is_star
2686
2687    @property
2688    def output_name(self):
2689        return self.alias
2690
2691
2692class TableSample(Expression):
2693    arg_types = {
2694        "this": False,
2695        "method": False,
2696        "bucket_numerator": False,
2697        "bucket_denominator": False,
2698        "bucket_field": False,
2699        "percent": False,
2700        "rows": False,
2701        "size": False,
2702        "seed": False,
2703        "kind": False,
2704    }
2705
2706
2707class Tag(Expression):
2708    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2709
2710    arg_types = {
2711        "this": False,
2712        "prefix": False,
2713        "postfix": False,
2714    }
2715
2716
2717class Pivot(Expression):
2718    arg_types = {
2719        "this": False,
2720        "alias": False,
2721        "expressions": True,
2722        "field": True,
2723        "unpivot": True,
2724    }
2725
2726
2727class Window(Expression):
2728    arg_types = {
2729        "this": True,
2730        "partition_by": False,
2731        "order": False,
2732        "spec": False,
2733        "alias": False,
2734    }
2735
2736
2737class WindowSpec(Expression):
2738    arg_types = {
2739        "kind": False,
2740        "start": False,
2741        "start_side": False,
2742        "end": False,
2743        "end_side": False,
2744    }
2745
2746
2747class Where(Expression):
2748    pass
2749
2750
2751class Star(Expression):
2752    arg_types = {"except": False, "replace": False}
2753
2754    @property
2755    def name(self) -> str:
2756        return "*"
2757
2758    @property
2759    def output_name(self):
2760        return self.name
2761
2762
2763class Parameter(Expression):
2764    arg_types = {"this": True, "wrapped": False}
2765
2766
2767class SessionParameter(Expression):
2768    arg_types = {"this": True, "kind": False}
2769
2770
2771class Placeholder(Expression):
2772    arg_types = {"this": False}
2773
2774
2775class Null(Condition):
2776    arg_types: t.Dict[str, t.Any] = {}
2777
2778    @property
2779    def name(self) -> str:
2780        return "NULL"
2781
2782
2783class Boolean(Condition):
2784    pass
2785
2786
2787class DataType(Expression):
2788    arg_types = {
2789        "this": True,
2790        "expressions": False,
2791        "nested": False,
2792        "values": False,
2793        "prefix": False,
2794    }
2795
2796    class Type(AutoName):
2797        CHAR = auto()
2798        NCHAR = auto()
2799        VARCHAR = auto()
2800        NVARCHAR = auto()
2801        TEXT = auto()
2802        MEDIUMTEXT = auto()
2803        LONGTEXT = auto()
2804        MEDIUMBLOB = auto()
2805        LONGBLOB = auto()
2806        BINARY = auto()
2807        VARBINARY = auto()
2808        INT = auto()
2809        UINT = auto()
2810        TINYINT = auto()
2811        UTINYINT = auto()
2812        SMALLINT = auto()
2813        USMALLINT = auto()
2814        BIGINT = auto()
2815        UBIGINT = auto()
2816        FLOAT = auto()
2817        DOUBLE = auto()
2818        DECIMAL = auto()
2819        BIT = auto()
2820        BOOLEAN = auto()
2821        JSON = auto()
2822        JSONB = auto()
2823        INTERVAL = auto()
2824        TIME = auto()
2825        TIMESTAMP = auto()
2826        TIMESTAMPTZ = auto()
2827        TIMESTAMPLTZ = auto()
2828        DATE = auto()
2829        DATETIME = auto()
2830        ARRAY = auto()
2831        MAP = auto()
2832        UUID = auto()
2833        GEOGRAPHY = auto()
2834        GEOMETRY = auto()
2835        STRUCT = auto()
2836        NULLABLE = auto()
2837        HLLSKETCH = auto()
2838        HSTORE = auto()
2839        SUPER = auto()
2840        SERIAL = auto()
2841        SMALLSERIAL = auto()
2842        BIGSERIAL = auto()
2843        XML = auto()
2844        UNIQUEIDENTIFIER = auto()
2845        MONEY = auto()
2846        SMALLMONEY = auto()
2847        ROWVERSION = auto()
2848        IMAGE = auto()
2849        VARIANT = auto()
2850        OBJECT = auto()
2851        INET = auto()
2852        NULL = auto()
2853        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2854
2855    TEXT_TYPES = {
2856        Type.CHAR,
2857        Type.NCHAR,
2858        Type.VARCHAR,
2859        Type.NVARCHAR,
2860        Type.TEXT,
2861    }
2862
2863    INTEGER_TYPES = {
2864        Type.INT,
2865        Type.TINYINT,
2866        Type.SMALLINT,
2867        Type.BIGINT,
2868    }
2869
2870    FLOAT_TYPES = {
2871        Type.FLOAT,
2872        Type.DOUBLE,
2873    }
2874
2875    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2876
2877    TEMPORAL_TYPES = {
2878        Type.TIMESTAMP,
2879        Type.TIMESTAMPTZ,
2880        Type.TIMESTAMPLTZ,
2881        Type.DATE,
2882        Type.DATETIME,
2883    }
2884
2885    @classmethod
2886    def build(
2887        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2888    ) -> DataType:
2889        from sqlglot import parse_one
2890
2891        if isinstance(dtype, str):
2892            if dtype.upper() in cls.Type.__members__:
2893                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2894            else:
2895                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2896            if data_type_exp is None:
2897                raise ValueError(f"Unparsable data type value: {dtype}")
2898        elif isinstance(dtype, DataType.Type):
2899            data_type_exp = DataType(this=dtype)
2900        elif isinstance(dtype, DataType):
2901            return dtype
2902        else:
2903            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2904        return DataType(**{**data_type_exp.args, **kwargs})
2905
2906    def is_type(self, dtype: DataType.Type) -> bool:
2907        return self.this == dtype
2908
2909
2910# https://www.postgresql.org/docs/15/datatype-pseudo.html
2911class PseudoType(Expression):
2912    pass
2913
2914
2915class StructKwarg(Expression):
2916    arg_types = {"this": True, "expression": True}
2917
2918
2919# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2920class SubqueryPredicate(Predicate):
2921    pass
2922
2923
2924class All(SubqueryPredicate):
2925    pass
2926
2927
2928class Any(SubqueryPredicate):
2929    pass
2930
2931
2932class Exists(SubqueryPredicate):
2933    pass
2934
2935
2936# Commands to interact with the databases or engines. For most of the command
2937# expressions we parse whatever comes after the command's name as a string.
2938class Command(Expression):
2939    arg_types = {"this": True, "expression": False}
2940
2941
2942class Transaction(Expression):
2943    arg_types = {"this": False, "modes": False}
2944
2945
2946class Commit(Expression):
2947    arg_types = {"chain": False}
2948
2949
2950class Rollback(Expression):
2951    arg_types = {"savepoint": False}
2952
2953
2954class AlterTable(Expression):
2955    arg_types = {"this": True, "actions": True, "exists": False}
2956
2957
2958class AddConstraint(Expression):
2959    arg_types = {"this": False, "expression": False, "enforced": False}
2960
2961
2962class DropPartition(Expression):
2963    arg_types = {"expressions": True, "exists": False}
2964
2965
2966# Binary expressions like (ADD a b)
2967class Binary(Expression):
2968    arg_types = {"this": True, "expression": True}
2969
2970    @property
2971    def left(self):
2972        return self.this
2973
2974    @property
2975    def right(self):
2976        return self.expression
2977
2978
2979class Add(Binary):
2980    pass
2981
2982
2983class Connector(Binary, Condition):
2984    pass
2985
2986
2987class And(Connector):
2988    pass
2989
2990
2991class Or(Connector):
2992    pass
2993
2994
2995class BitwiseAnd(Binary):
2996    pass
2997
2998
2999class BitwiseLeftShift(Binary):
3000    pass
3001
3002
3003class BitwiseOr(Binary):
3004    pass
3005
3006
3007class BitwiseRightShift(Binary):
3008    pass
3009
3010
3011class BitwiseXor(Binary):
3012    pass
3013
3014
3015class Div(Binary):
3016    pass
3017
3018
3019class Overlaps(Binary):
3020    pass
3021
3022
3023class Dot(Binary):
3024    @property
3025    def name(self) -> str:
3026        return self.expression.name
3027
3028    @classmethod
3029    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3030        """Build a Dot object with a sequence of expressions."""
3031        if len(expressions) < 2:
3032            raise ValueError(f"Dot requires >= 2 expressions.")
3033
3034        a, b, *expressions = expressions
3035        dot = Dot(this=a, expression=b)
3036
3037        for expression in expressions:
3038            dot = Dot(this=dot, expression=expression)
3039
3040        return dot
3041
3042
3043class DPipe(Binary):
3044    pass
3045
3046
3047class EQ(Binary, Predicate):
3048    pass
3049
3050
3051class NullSafeEQ(Binary, Predicate):
3052    pass
3053
3054
3055class NullSafeNEQ(Binary, Predicate):
3056    pass
3057
3058
3059class Distance(Binary):
3060    pass
3061
3062
3063class Escape(Binary):
3064    pass
3065
3066
3067class Glob(Binary, Predicate):
3068    pass
3069
3070
3071class GT(Binary, Predicate):
3072    pass
3073
3074
3075class GTE(Binary, Predicate):
3076    pass
3077
3078
3079class ILike(Binary, Predicate):
3080    pass
3081
3082
3083class ILikeAny(Binary, Predicate):
3084    pass
3085
3086
3087class IntDiv(Binary):
3088    pass
3089
3090
3091class Is(Binary, Predicate):
3092    pass
3093
3094
3095class Kwarg(Binary):
3096    """Kwarg in special functions like func(kwarg => y)."""
3097
3098
3099class Like(Binary, Predicate):
3100    pass
3101
3102
3103class LikeAny(Binary, Predicate):
3104    pass
3105
3106
3107class LT(Binary, Predicate):
3108    pass
3109
3110
3111class LTE(Binary, Predicate):
3112    pass
3113
3114
3115class Mod(Binary):
3116    pass
3117
3118
3119class Mul(Binary):
3120    pass
3121
3122
3123class NEQ(Binary, Predicate):
3124    pass
3125
3126
3127class SimilarTo(Binary, Predicate):
3128    pass
3129
3130
3131class Slice(Binary):
3132    arg_types = {"this": False, "expression": False}
3133
3134
3135class Sub(Binary):
3136    pass
3137
3138
3139class ArrayOverlaps(Binary):
3140    pass
3141
3142
3143# Unary Expressions
3144# (NOT a)
3145class Unary(Expression):
3146    pass
3147
3148
3149class BitwiseNot(Unary):
3150    pass
3151
3152
3153class Not(Unary, Condition):
3154    pass
3155
3156
3157class Paren(Unary, Condition):
3158    arg_types = {"this": True, "with": False}
3159
3160
3161class Neg(Unary):
3162    pass
3163
3164
3165# Special Functions
3166class Alias(Expression):
3167    arg_types = {"this": True, "alias": False}
3168
3169    @property
3170    def output_name(self):
3171        return self.alias
3172
3173
3174class Aliases(Expression):
3175    arg_types = {"this": True, "expressions": True}
3176
3177    @property
3178    def aliases(self):
3179        return self.expressions
3180
3181
3182class AtTimeZone(Expression):
3183    arg_types = {"this": True, "zone": True}
3184
3185
3186class Between(Predicate):
3187    arg_types = {"this": True, "low": True, "high": True}
3188
3189
3190class Bracket(Condition):
3191    arg_types = {"this": True, "expressions": True}
3192
3193
3194class Distinct(Expression):
3195    arg_types = {"expressions": False, "on": False}
3196
3197
3198class In(Predicate):
3199    arg_types = {
3200        "this": True,
3201        "expressions": False,
3202        "query": False,
3203        "unnest": False,
3204        "field": False,
3205        "is_global": False,
3206    }
3207
3208
3209class TimeUnit(Expression):
3210    """Automatically converts unit arg into a var."""
3211
3212    arg_types = {"unit": False}
3213
3214    def __init__(self, **args):
3215        unit = args.get("unit")
3216        if isinstance(unit, (Column, Literal)):
3217            args["unit"] = Var(this=unit.name)
3218        elif isinstance(unit, Week):
3219            unit.set("this", Var(this=unit.this.name))
3220        super().__init__(**args)
3221
3222
3223class Interval(TimeUnit):
3224    arg_types = {"this": False, "unit": False}
3225
3226
3227class IgnoreNulls(Expression):
3228    pass
3229
3230
3231class RespectNulls(Expression):
3232    pass
3233
3234
3235# Functions
3236class Func(Condition):
3237    """
3238    The base class for all function expressions.
3239
3240    Attributes:
3241        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3242            treated as a variable length argument and the argument's value will be stored as a list.
3243        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3244            for this function expression. These values are used to map this node to a name during parsing
3245            as well as to provide the function's name during SQL string generation. By default the SQL
3246            name is set to the expression's class name transformed to snake case.
3247    """
3248
3249    is_var_len_args = False
3250
3251    @classmethod
3252    def from_arg_list(cls, args):
3253        if cls.is_var_len_args:
3254            all_arg_keys = list(cls.arg_types)
3255            # If this function supports variable length argument treat the last argument as such.
3256            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3257            num_non_var = len(non_var_len_arg_keys)
3258
3259            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3260            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3261        else:
3262            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3263
3264        return cls(**args_dict)
3265
3266    @classmethod
3267    def sql_names(cls):
3268        if cls is Func:
3269            raise NotImplementedError(
3270                "SQL name is only supported by concrete function implementations"
3271            )
3272        if "_sql_names" not in cls.__dict__:
3273            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3274        return cls._sql_names
3275
3276    @classmethod
3277    def sql_name(cls):
3278        return cls.sql_names()[0]
3279
3280    @classmethod
3281    def default_parser_mappings(cls):
3282        return {name: cls.from_arg_list for name in cls.sql_names()}
3283
3284
3285class AggFunc(Func):
3286    pass
3287
3288
3289class Abs(Func):
3290    pass
3291
3292
3293class Anonymous(Func):
3294    arg_types = {"this": True, "expressions": False}
3295    is_var_len_args = True
3296
3297
3298# https://docs.snowflake.com/en/sql-reference/functions/hll
3299# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3300class Hll(AggFunc):
3301    arg_types = {"this": True, "expressions": False}
3302    is_var_len_args = True
3303
3304
3305class ApproxDistinct(AggFunc):
3306    arg_types = {"this": True, "accuracy": False}
3307
3308
3309class Array(Func):
3310    arg_types = {"expressions": False}
3311    is_var_len_args = True
3312
3313
3314# https://docs.snowflake.com/en/sql-reference/functions/to_char
3315class ToChar(Func):
3316    arg_types = {"this": True, "format": False}
3317
3318
3319class GenerateSeries(Func):
3320    arg_types = {"start": True, "end": True, "step": False}
3321
3322
3323class ArrayAgg(AggFunc):
3324    pass
3325
3326
3327class ArrayAll(Func):
3328    arg_types = {"this": True, "expression": True}
3329
3330
3331class ArrayAny(Func):
3332    arg_types = {"this": True, "expression": True}
3333
3334
3335class ArrayConcat(Func):
3336    arg_types = {"this": True, "expressions": False}
3337    is_var_len_args = True
3338
3339
3340class ArrayContains(Binary, Func):
3341    pass
3342
3343
3344class ArrayContained(Binary):
3345    pass
3346
3347
3348class ArrayFilter(Func):
3349    arg_types = {"this": True, "expression": True}
3350    _sql_names = ["FILTER", "ARRAY_FILTER"]
3351
3352
3353class ArrayJoin(Func):
3354    arg_types = {"this": True, "expression": True, "null": False}
3355
3356
3357class ArraySize(Func):
3358    arg_types = {"this": True, "expression": False}
3359
3360
3361class ArraySort(Func):
3362    arg_types = {"this": True, "expression": False}
3363
3364
3365class ArraySum(Func):
3366    pass
3367
3368
3369class ArrayUnionAgg(AggFunc):
3370    pass
3371
3372
3373class Avg(AggFunc):
3374    pass
3375
3376
3377class AnyValue(AggFunc):
3378    pass
3379
3380
3381class Case(Func):
3382    arg_types = {"this": False, "ifs": True, "default": False}
3383
3384
3385class Cast(Func):
3386    arg_types = {"this": True, "to": True}
3387
3388    @property
3389    def name(self) -> str:
3390        return self.this.name
3391
3392    @property
3393    def to(self):
3394        return self.args["to"]
3395
3396    @property
3397    def output_name(self):
3398        return self.name
3399
3400    def is_type(self, dtype: DataType.Type) -> bool:
3401        return self.to.is_type(dtype)
3402
3403
3404class Collate(Binary):
3405    pass
3406
3407
3408class TryCast(Cast):
3409    pass
3410
3411
3412class Ceil(Func):
3413    arg_types = {"this": True, "decimals": False}
3414    _sql_names = ["CEIL", "CEILING"]
3415
3416
3417class Coalesce(Func):
3418    arg_types = {"this": True, "expressions": False}
3419    is_var_len_args = True
3420
3421
3422class Concat(Func):
3423    arg_types = {"expressions": True}
3424    is_var_len_args = True
3425
3426
3427class ConcatWs(Concat):
3428    _sql_names = ["CONCAT_WS"]
3429
3430
3431class Count(AggFunc):
3432    arg_types = {"this": False}
3433
3434
3435class CountIf(AggFunc):
3436    pass
3437
3438
3439class CurrentDate(Func):
3440    arg_types = {"this": False}
3441
3442
3443class CurrentDatetime(Func):
3444    arg_types = {"this": False}
3445
3446
3447class CurrentTime(Func):
3448    arg_types = {"this": False}
3449
3450
3451class CurrentTimestamp(Func):
3452    arg_types = {"this": False}
3453
3454
3455class CurrentUser(Func):
3456    arg_types = {"this": False}
3457
3458
3459class DateAdd(Func, TimeUnit):
3460    arg_types = {"this": True, "expression": True, "unit": False}
3461
3462
3463class DateSub(Func, TimeUnit):
3464    arg_types = {"this": True, "expression": True, "unit": False}
3465
3466
3467class DateDiff(Func, TimeUnit):
3468    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3469    arg_types = {"this": True, "expression": True, "unit": False}
3470
3471
3472class DateTrunc(Func):
3473    arg_types = {"unit": True, "this": True, "zone": False}
3474
3475
3476class DatetimeAdd(Func, TimeUnit):
3477    arg_types = {"this": True, "expression": True, "unit": False}
3478
3479
3480class DatetimeSub(Func, TimeUnit):
3481    arg_types = {"this": True, "expression": True, "unit": False}
3482
3483
3484class DatetimeDiff(Func, TimeUnit):
3485    arg_types = {"this": True, "expression": True, "unit": False}
3486
3487
3488class DatetimeTrunc(Func, TimeUnit):
3489    arg_types = {"this": True, "unit": True, "zone": False}
3490
3491
3492class DayOfWeek(Func):
3493    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3494
3495
3496class DayOfMonth(Func):
3497    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3498
3499
3500class DayOfYear(Func):
3501    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3502
3503
3504class WeekOfYear(Func):
3505    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3506
3507
3508class LastDateOfMonth(Func):
3509    pass
3510
3511
3512class Extract(Func):
3513    arg_types = {"this": True, "expression": True}
3514
3515
3516class TimestampAdd(Func, TimeUnit):
3517    arg_types = {"this": True, "expression": True, "unit": False}
3518
3519
3520class TimestampSub(Func, TimeUnit):
3521    arg_types = {"this": True, "expression": True, "unit": False}
3522
3523
3524class TimestampDiff(Func, TimeUnit):
3525    arg_types = {"this": True, "expression": True, "unit": False}
3526
3527
3528class TimestampTrunc(Func, TimeUnit):
3529    arg_types = {"this": True, "unit": True, "zone": False}
3530
3531
3532class TimeAdd(Func, TimeUnit):
3533    arg_types = {"this": True, "expression": True, "unit": False}
3534
3535
3536class TimeSub(Func, TimeUnit):
3537    arg_types = {"this": True, "expression": True, "unit": False}
3538
3539
3540class TimeDiff(Func, TimeUnit):
3541    arg_types = {"this": True, "expression": True, "unit": False}
3542
3543
3544class TimeTrunc(Func, TimeUnit):
3545    arg_types = {"this": True, "unit": True, "zone": False}
3546
3547
3548class DateFromParts(Func):
3549    _sql_names = ["DATEFROMPARTS"]
3550    arg_types = {"year": True, "month": True, "day": True}
3551
3552
3553class DateStrToDate(Func):
3554    pass
3555
3556
3557class DateToDateStr(Func):
3558    pass
3559
3560
3561class DateToDi(Func):
3562    pass
3563
3564
3565class Day(Func):
3566    pass
3567
3568
3569class Decode(Func):
3570    arg_types = {"this": True, "charset": True, "replace": False}
3571
3572
3573class DiToDate(Func):
3574    pass
3575
3576
3577class Encode(Func):
3578    arg_types = {"this": True, "charset": True}
3579
3580
3581class Exp(Func):
3582    pass
3583
3584
3585class Explode(Func):
3586    pass
3587
3588
3589class ExponentialTimeDecayedAvg(AggFunc):
3590    arg_types = {"this": True, "time": False, "decay": False}
3591
3592
3593class Floor(Func):
3594    arg_types = {"this": True, "decimals": False}
3595
3596
3597class Greatest(Func):
3598    arg_types = {"this": True, "expressions": False}
3599    is_var_len_args = True
3600
3601
3602class GroupConcat(Func):
3603    arg_types = {"this": True, "separator": False}
3604
3605
3606class GroupUniqArray(AggFunc):
3607    arg_types = {"this": True, "size": False}
3608
3609
3610class Hex(Func):
3611    pass
3612
3613
3614class Histogram(AggFunc):
3615    arg_types = {"this": True, "bins": False}
3616
3617
3618class If(Func):
3619    arg_types = {"this": True, "true": True, "false": False}
3620
3621
3622class IfNull(Func):
3623    arg_types = {"this": True, "expression": False}
3624    _sql_names = ["IFNULL", "NVL"]
3625
3626
3627class Initcap(Func):
3628    pass
3629
3630
3631class JSONKeyValue(Expression):
3632    arg_types = {"this": True, "expression": True}
3633
3634
3635class JSONObject(Func):
3636    arg_types = {
3637        "expressions": False,
3638        "null_handling": False,
3639        "unique_keys": False,
3640        "return_type": False,
3641        "format_json": False,
3642        "encoding": False,
3643    }
3644
3645
3646class JSONBContains(Binary):
3647    _sql_names = ["JSONB_CONTAINS"]
3648
3649
3650class JSONExtract(Binary, Func):
3651    _sql_names = ["JSON_EXTRACT"]
3652
3653
3654class JSONExtractScalar(JSONExtract):
3655    _sql_names = ["JSON_EXTRACT_SCALAR"]
3656
3657
3658class JSONBExtract(JSONExtract):
3659    _sql_names = ["JSONB_EXTRACT"]
3660
3661
3662class JSONBExtractScalar(JSONExtract):
3663    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3664
3665
3666class JSONFormat(Func):
3667    arg_types = {"this": False, "options": False}
3668    _sql_names = ["JSON_FORMAT"]
3669
3670
3671class Least(Func):
3672    arg_types = {"expressions": False}
3673    is_var_len_args = True
3674
3675
3676class Length(Func):
3677    pass
3678
3679
3680class Levenshtein(Func):
3681    arg_types = {
3682        "this": True,
3683        "expression": False,
3684        "ins_cost": False,
3685        "del_cost": False,
3686        "sub_cost": False,
3687    }
3688
3689
3690class Ln(Func):
3691    pass
3692
3693
3694class Log(Func):
3695    arg_types = {"this": True, "expression": False}
3696
3697
3698class Log2(Func):
3699    pass
3700
3701
3702class Log10(Func):
3703    pass
3704
3705
3706class LogicalOr(AggFunc):
3707    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3708
3709
3710class LogicalAnd(AggFunc):
3711    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3712
3713
3714class Lower(Func):
3715    _sql_names = ["LOWER", "LCASE"]
3716
3717
3718class Map(Func):
3719    arg_types = {"keys": False, "values": False}
3720
3721
3722class VarMap(Func):
3723    arg_types = {"keys": True, "values": True}
3724    is_var_len_args = True
3725
3726
3727# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
3728class MatchAgainst(Func):
3729    arg_types = {"this": True, "expressions": True, "modifier": False}
3730
3731
3732class Max(AggFunc):
3733    arg_types = {"this": True, "expressions": False}
3734    is_var_len_args = True
3735
3736
3737class Min(AggFunc):
3738    arg_types = {"this": True, "expressions": False}
3739    is_var_len_args = True
3740
3741
3742class Month(Func):
3743    pass
3744
3745
3746class Nvl2(Func):
3747    arg_types = {"this": True, "true": True, "false": False}
3748
3749
3750class Posexplode(Func):
3751    pass
3752
3753
3754class Pow(Binary, Func):
3755    _sql_names = ["POWER", "POW"]
3756
3757
3758class PercentileCont(AggFunc):
3759    pass
3760
3761
3762class PercentileDisc(AggFunc):
3763    pass
3764
3765
3766class Quantile(AggFunc):
3767    arg_types = {"this": True, "quantile": True}
3768
3769
3770# Clickhouse-specific:
3771# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3772class Quantiles(AggFunc):
3773    arg_types = {"parameters": True, "expressions": True}
3774    is_var_len_args = True
3775
3776
3777class QuantileIf(AggFunc):
3778    arg_types = {"parameters": True, "expressions": True}
3779
3780
3781class ApproxQuantile(Quantile):
3782    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3783
3784
3785class RangeN(Func):
3786    arg_types = {"this": True, "expressions": True, "each": False}
3787
3788
3789class ReadCSV(Func):
3790    _sql_names = ["READ_CSV"]
3791    is_var_len_args = True
3792    arg_types = {"this": True, "expressions": False}
3793
3794
3795class Reduce(Func):
3796    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3797
3798
3799class RegexpExtract(Func):
3800    arg_types = {
3801        "this": True,
3802        "expression": True,
3803        "position": False,
3804        "occurrence": False,
3805        "group": False,
3806    }
3807
3808
3809class RegexpLike(Func):
3810    arg_types = {"this": True, "expression": True, "flag": False}
3811
3812
3813class RegexpILike(Func):
3814    arg_types = {"this": True, "expression": True, "flag": False}
3815
3816
3817# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
3818# limit is the number of times a pattern is applied
3819class RegexpSplit(Func):
3820    arg_types = {"this": True, "expression": True, "limit": False}
3821
3822
3823class Repeat(Func):
3824    arg_types = {"this": True, "times": True}
3825
3826
3827class Round(Func):
3828    arg_types = {"this": True, "decimals": False}
3829
3830
3831class RowNumber(Func):
3832    arg_types: t.Dict[str, t.Any] = {}
3833
3834
3835class SafeDivide(Func):
3836    arg_types = {"this": True, "expression": True}
3837
3838
3839class SetAgg(AggFunc):
3840    pass
3841
3842
3843class SortArray(Func):
3844    arg_types = {"this": True, "asc": False}
3845
3846
3847class Split(Func):
3848    arg_types = {"this": True, "expression": True, "limit": False}
3849
3850
3851# Start may be omitted in the case of postgres
3852# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3853class Substring(Func):
3854    arg_types = {"this": True, "start": False, "length": False}
3855
3856
3857class StrPosition(Func):
3858    arg_types = {
3859        "this": True,
3860        "substr": True,
3861        "position": False,
3862        "instance": False,
3863    }
3864
3865
3866class StrToDate(Func):
3867    arg_types = {"this": True, "format": True}
3868
3869
3870class StrToTime(Func):
3871    arg_types = {"this": True, "format": True}
3872
3873
3874# Spark allows unix_timestamp()
3875# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3876class StrToUnix(Func):
3877    arg_types = {"this": False, "format": False}
3878
3879
3880class NumberToStr(Func):
3881    arg_types = {"this": True, "format": True}
3882
3883
3884class Struct(Func):
3885    arg_types = {"expressions": True}
3886    is_var_len_args = True
3887
3888
3889class StructExtract(Func):
3890    arg_types = {"this": True, "expression": True}
3891
3892
3893class Sum(AggFunc):
3894    pass
3895
3896
3897class Sqrt(Func):
3898    pass
3899
3900
3901class Stddev(AggFunc):
3902    pass
3903
3904
3905class StddevPop(AggFunc):
3906    pass
3907
3908
3909class StddevSamp(AggFunc):
3910    pass
3911
3912
3913class TimeToStr(Func):
3914    arg_types = {"this": True, "format": True}
3915
3916
3917class TimeToTimeStr(Func):
3918    pass
3919
3920
3921class TimeToUnix(Func):
3922    pass
3923
3924
3925class TimeStrToDate(Func):
3926    pass
3927
3928
3929class TimeStrToTime(Func):
3930    pass
3931
3932
3933class TimeStrToUnix(Func):
3934    pass
3935
3936
3937class Trim(Func):
3938    arg_types = {
3939        "this": True,
3940        "expression": False,
3941        "position": False,
3942        "collation": False,
3943    }
3944
3945
3946class TsOrDsAdd(Func, TimeUnit):
3947    arg_types = {"this": True, "expression": True, "unit": False}
3948
3949
3950class TsOrDsToDateStr(Func):
3951    pass
3952
3953
3954class TsOrDsToDate(Func):
3955    arg_types = {"this": True, "format": False}
3956
3957
3958class TsOrDiToDi(Func):
3959    pass
3960
3961
3962class Unhex(Func):
3963    pass
3964
3965
3966class UnixToStr(Func):
3967    arg_types = {"this": True, "format": False}
3968
3969
3970# https://prestodb.io/docs/current/functions/datetime.html
3971# presto has weird zone/hours/minutes
3972class UnixToTime(Func):
3973    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3974
3975    SECONDS = Literal.string("seconds")
3976    MILLIS = Literal.string("millis")
3977    MICROS = Literal.string("micros")
3978
3979
3980class UnixToTimeStr(Func):
3981    pass
3982
3983
3984class Upper(Func):
3985    _sql_names = ["UPPER", "UCASE"]
3986
3987
3988class Variance(AggFunc):
3989    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
3990
3991
3992class VariancePop(AggFunc):
3993    _sql_names = ["VARIANCE_POP", "VAR_POP"]
3994
3995
3996class Week(Func):
3997    arg_types = {"this": True, "mode": False}
3998
3999
4000class XMLTable(Func):
4001    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4002
4003
4004class Year(Func):
4005    pass
4006
4007
4008class Use(Expression):
4009    arg_types = {"this": True, "kind": False}
4010
4011
4012class Merge(Expression):
4013    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4014
4015
4016class When(Func):
4017    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4018
4019
4020def _norm_arg(arg):
4021    return arg.lower() if type(arg) is str else arg
4022
4023
4024ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4025
4026
4027# Helpers
4028def maybe_parse(
4029    sql_or_expression: ExpOrStr,
4030    *,
4031    into: t.Optional[IntoType] = None,
4032    dialect: DialectType = None,
4033    prefix: t.Optional[str] = None,
4034    copy: bool = False,
4035    **opts,
4036) -> Expression:
4037    """Gracefully handle a possible string or expression.
4038
4039    Example:
4040        >>> maybe_parse("1")
4041        (LITERAL this: 1, is_string: False)
4042        >>> maybe_parse(to_identifier("x"))
4043        (IDENTIFIER this: x, quoted: False)
4044
4045    Args:
4046        sql_or_expression: the SQL code string or an expression
4047        into: the SQLGlot Expression to parse into
4048        dialect: the dialect used to parse the input expressions (in the case that an
4049            input expression is a SQL string).
4050        prefix: a string to prefix the sql with before it gets parsed
4051            (automatically includes a space)
4052        copy: whether or not to copy the expression.
4053        **opts: other options to use to parse the input expressions (again, in the case
4054            that an input expression is a SQL string).
4055
4056    Returns:
4057        Expression: the parsed or given expression.
4058    """
4059    if isinstance(sql_or_expression, Expression):
4060        if copy:
4061            return sql_or_expression.copy()
4062        return sql_or_expression
4063
4064    import sqlglot
4065
4066    sql = str(sql_or_expression)
4067    if prefix:
4068        sql = f"{prefix} {sql}"
4069    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4070
4071
4072def _maybe_copy(instance, copy=True):
4073    return instance.copy() if copy else instance
4074
4075
4076def _is_wrong_expression(expression, into):
4077    return isinstance(expression, Expression) and not isinstance(expression, into)
4078
4079
4080def _apply_builder(
4081    expression,
4082    instance,
4083    arg,
4084    copy=True,
4085    prefix=None,
4086    into=None,
4087    dialect=None,
4088    **opts,
4089):
4090    if _is_wrong_expression(expression, into):
4091        expression = into(this=expression)
4092    instance = _maybe_copy(instance, copy)
4093    expression = maybe_parse(
4094        sql_or_expression=expression,
4095        prefix=prefix,
4096        into=into,
4097        dialect=dialect,
4098        **opts,
4099    )
4100    instance.set(arg, expression)
4101    return instance
4102
4103
4104def _apply_child_list_builder(
4105    *expressions,
4106    instance,
4107    arg,
4108    append=True,
4109    copy=True,
4110    prefix=None,
4111    into=None,
4112    dialect=None,
4113    properties=None,
4114    **opts,
4115):
4116    instance = _maybe_copy(instance, copy)
4117    parsed = []
4118    for expression in expressions:
4119        if _is_wrong_expression(expression, into):
4120            expression = into(expressions=[expression])
4121        expression = maybe_parse(
4122            expression,
4123            into=into,
4124            dialect=dialect,
4125            prefix=prefix,
4126            **opts,
4127        )
4128        parsed.extend(expression.expressions)
4129
4130    existing = instance.args.get(arg)
4131    if append and existing:
4132        parsed = existing.expressions + parsed
4133
4134    child = into(expressions=parsed)
4135    for k, v in (properties or {}).items():
4136        child.set(k, v)
4137    instance.set(arg, child)
4138    return instance
4139
4140
4141def _apply_list_builder(
4142    *expressions,
4143    instance,
4144    arg,
4145    append=True,
4146    copy=True,
4147    prefix=None,
4148    into=None,
4149    dialect=None,
4150    **opts,
4151):
4152    inst = _maybe_copy(instance, copy)
4153
4154    expressions = [
4155        maybe_parse(
4156            sql_or_expression=expression,
4157            into=into,
4158            prefix=prefix,
4159            dialect=dialect,
4160            **opts,
4161        )
4162        for expression in expressions
4163    ]
4164
4165    existing_expressions = inst.args.get(arg)
4166    if append and existing_expressions:
4167        expressions = existing_expressions + expressions
4168
4169    inst.set(arg, expressions)
4170    return inst
4171
4172
4173def _apply_conjunction_builder(
4174    *expressions,
4175    instance,
4176    arg,
4177    into=None,
4178    append=True,
4179    copy=True,
4180    dialect=None,
4181    **opts,
4182):
4183    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4184    if not expressions:
4185        return instance
4186
4187    inst = _maybe_copy(instance, copy)
4188
4189    existing = inst.args.get(arg)
4190    if append and existing is not None:
4191        expressions = [existing.this if into else existing] + list(expressions)
4192
4193    node = and_(*expressions, dialect=dialect, **opts)
4194
4195    inst.set(arg, into(this=node) if into else node)
4196    return inst
4197
4198
4199def _combine(expressions, operator, dialect=None, **opts):
4200    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4201    this = expressions[0]
4202    if expressions[1:]:
4203        this = _wrap_operator(this)
4204    for expression in expressions[1:]:
4205        this = operator(this=this, expression=_wrap_operator(expression))
4206    return this
4207
4208
4209def _wrap_operator(expression):
4210    if isinstance(expression, (And, Or, Not)):
4211        expression = Paren(this=expression)
4212    return expression
4213
4214
4215def union(left, right, distinct=True, dialect=None, **opts):
4216    """
4217    Initializes a syntax tree from one UNION expression.
4218
4219    Example:
4220        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4221        'SELECT * FROM foo UNION SELECT * FROM bla'
4222
4223    Args:
4224        left (str | Expression): the SQL code string corresponding to the left-hand side.
4225            If an `Expression` instance is passed, it will be used as-is.
4226        right (str | Expression): the SQL code string corresponding to the right-hand side.
4227            If an `Expression` instance is passed, it will be used as-is.
4228        distinct (bool): set the DISTINCT flag if and only if this is true.
4229        dialect (str): the dialect used to parse the input expression.
4230        opts (kwargs): other options to use to parse the input expressions.
4231    Returns:
4232        Union: the syntax tree for the UNION expression.
4233    """
4234    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4235    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4236
4237    return Union(this=left, expression=right, distinct=distinct)
4238
4239
4240def intersect(left, right, distinct=True, dialect=None, **opts):
4241    """
4242    Initializes a syntax tree from one INTERSECT expression.
4243
4244    Example:
4245        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4246        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4247
4248    Args:
4249        left (str | Expression): the SQL code string corresponding to the left-hand side.
4250            If an `Expression` instance is passed, it will be used as-is.
4251        right (str | Expression): the SQL code string corresponding to the right-hand side.
4252            If an `Expression` instance is passed, it will be used as-is.
4253        distinct (bool): set the DISTINCT flag if and only if this is true.
4254        dialect (str): the dialect used to parse the input expression.
4255        opts (kwargs): other options to use to parse the input expressions.
4256    Returns:
4257        Intersect: the syntax tree for the INTERSECT expression.
4258    """
4259    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4260    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4261
4262    return Intersect(this=left, expression=right, distinct=distinct)
4263
4264
4265def except_(left, right, distinct=True, dialect=None, **opts):
4266    """
4267    Initializes a syntax tree from one EXCEPT expression.
4268
4269    Example:
4270        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4271        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4272
4273    Args:
4274        left (str | Expression): the SQL code string corresponding to the left-hand side.
4275            If an `Expression` instance is passed, it will be used as-is.
4276        right (str | Expression): the SQL code string corresponding to the right-hand side.
4277            If an `Expression` instance is passed, it will be used as-is.
4278        distinct (bool): set the DISTINCT flag if and only if this is true.
4279        dialect (str): the dialect used to parse the input expression.
4280        opts (kwargs): other options to use to parse the input expressions.
4281    Returns:
4282        Except: the syntax tree for the EXCEPT statement.
4283    """
4284    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4285    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4286
4287    return Except(this=left, expression=right, distinct=distinct)
4288
4289
4290def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4291    """
4292    Initializes a syntax tree from one or multiple SELECT expressions.
4293
4294    Example:
4295        >>> select("col1", "col2").from_("tbl").sql()
4296        'SELECT col1, col2 FROM tbl'
4297
4298    Args:
4299        *expressions: the SQL code string to parse as the expressions of a
4300            SELECT statement. If an Expression instance is passed, this is used as-is.
4301        dialect: the dialect used to parse the input expressions (in the case that an
4302            input expression is a SQL string).
4303        **opts: other options to use to parse the input expressions (again, in the case
4304            that an input expression is a SQL string).
4305
4306    Returns:
4307        Select: the syntax tree for the SELECT statement.
4308    """
4309    return Select().select(*expressions, dialect=dialect, **opts)
4310
4311
4312def from_(*expressions, dialect=None, **opts) -> Select:
4313    """
4314    Initializes a syntax tree from a FROM expression.
4315
4316    Example:
4317        >>> from_("tbl").select("col1", "col2").sql()
4318        'SELECT col1, col2 FROM tbl'
4319
4320    Args:
4321        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4322            SELECT statement. If an Expression instance is passed, this is used as-is.
4323        dialect (str): the dialect used to parse the input expression (in the case that the
4324            input expression is a SQL string).
4325        **opts: other options to use to parse the input expressions (again, in the case
4326            that the input expression is a SQL string).
4327
4328    Returns:
4329        Select: the syntax tree for the SELECT statement.
4330    """
4331    return Select().from_(*expressions, dialect=dialect, **opts)
4332
4333
4334def update(
4335    table: str | Table,
4336    properties: dict,
4337    where: t.Optional[ExpOrStr] = None,
4338    from_: t.Optional[ExpOrStr] = None,
4339    dialect: DialectType = None,
4340    **opts,
4341) -> Update:
4342    """
4343    Creates an update statement.
4344
4345    Example:
4346        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4347        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4348
4349    Args:
4350        *properties: dictionary of properties to set which are
4351            auto converted to sql objects eg None -> NULL
4352        where: sql conditional parsed into a WHERE statement
4353        from_: sql statement parsed into a FROM statement
4354        dialect: the dialect used to parse the input expressions.
4355        **opts: other options to use to parse the input expressions.
4356
4357    Returns:
4358        Update: the syntax tree for the UPDATE statement.
4359    """
4360    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4361    update_expr.set(
4362        "expressions",
4363        [
4364            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4365            for k, v in properties.items()
4366        ],
4367    )
4368    if from_:
4369        update_expr.set(
4370            "from",
4371            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4372        )
4373    if isinstance(where, Condition):
4374        where = Where(this=where)
4375    if where:
4376        update_expr.set(
4377            "where",
4378            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4379        )
4380    return update_expr
4381
4382
4383def delete(
4384    table: ExpOrStr,
4385    where: t.Optional[ExpOrStr] = None,
4386    returning: t.Optional[ExpOrStr] = None,
4387    dialect: DialectType = None,
4388    **opts,
4389) -> Delete:
4390    """
4391    Builds a delete statement.
4392
4393    Example:
4394        >>> delete("my_table", where="id > 1").sql()
4395        'DELETE FROM my_table WHERE id > 1'
4396
4397    Args:
4398        where: sql conditional parsed into a WHERE statement
4399        returning: sql conditional parsed into a RETURNING statement
4400        dialect: the dialect used to parse the input expressions.
4401        **opts: other options to use to parse the input expressions.
4402
4403    Returns:
4404        Delete: the syntax tree for the DELETE statement.
4405    """
4406    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4407    if where:
4408        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4409    if returning:
4410        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4411    return delete_expr
4412
4413
4414def condition(expression, dialect=None, **opts) -> Condition:
4415    """
4416    Initialize a logical condition expression.
4417
4418    Example:
4419        >>> condition("x=1").sql()
4420        'x = 1'
4421
4422        This is helpful for composing larger logical syntax trees:
4423        >>> where = condition("x=1")
4424        >>> where = where.and_("y=1")
4425        >>> Select().from_("tbl").select("*").where(where).sql()
4426        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4427
4428    Args:
4429        *expression (str | Expression): the SQL code string to parse.
4430            If an Expression instance is passed, this is used as-is.
4431        dialect (str): the dialect used to parse the input expression (in the case that the
4432            input expression is a SQL string).
4433        **opts: other options to use to parse the input expressions (again, in the case
4434            that the input expression is a SQL string).
4435
4436    Returns:
4437        Condition: the expression
4438    """
4439    return maybe_parse(  # type: ignore
4440        expression,
4441        into=Condition,
4442        dialect=dialect,
4443        **opts,
4444    )
4445
4446
4447def and_(*expressions, dialect=None, **opts) -> And:
4448    """
4449    Combine multiple conditions with an AND logical operator.
4450
4451    Example:
4452        >>> and_("x=1", and_("y=1", "z=1")).sql()
4453        'x = 1 AND (y = 1 AND z = 1)'
4454
4455    Args:
4456        *expressions (str | Expression): the SQL code strings to parse.
4457            If an Expression instance is passed, this is used as-is.
4458        dialect (str): the dialect used to parse the input expression.
4459        **opts: other options to use to parse the input expressions.
4460
4461    Returns:
4462        And: the new condition
4463    """
4464    return _combine(expressions, And, dialect, **opts)
4465
4466
4467def or_(*expressions, dialect=None, **opts) -> Or:
4468    """
4469    Combine multiple conditions with an OR logical operator.
4470
4471    Example:
4472        >>> or_("x=1", or_("y=1", "z=1")).sql()
4473        'x = 1 OR (y = 1 OR z = 1)'
4474
4475    Args:
4476        *expressions (str | Expression): the SQL code strings to parse.
4477            If an Expression instance is passed, this is used as-is.
4478        dialect (str): the dialect used to parse the input expression.
4479        **opts: other options to use to parse the input expressions.
4480
4481    Returns:
4482        Or: the new condition
4483    """
4484    return _combine(expressions, Or, dialect, **opts)
4485
4486
4487def not_(expression, dialect=None, **opts) -> Not:
4488    """
4489    Wrap a condition with a NOT operator.
4490
4491    Example:
4492        >>> not_("this_suit='black'").sql()
4493        "NOT this_suit = 'black'"
4494
4495    Args:
4496        expression (str | Expression): the SQL code strings to parse.
4497            If an Expression instance is passed, this is used as-is.
4498        dialect (str): the dialect used to parse the input expression.
4499        **opts: other options to use to parse the input expressions.
4500
4501    Returns:
4502        Not: the new condition
4503    """
4504    this = condition(
4505        expression,
4506        dialect=dialect,
4507        **opts,
4508    )
4509    return Not(this=_wrap_operator(this))
4510
4511
4512def paren(expression) -> Paren:
4513    return Paren(this=expression)
4514
4515
4516SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4517
4518
4519@t.overload
4520def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4521    ...
4522
4523
4524@t.overload
4525def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4526    ...
4527
4528
4529def to_identifier(name, quoted=None):
4530    """Builds an identifier.
4531
4532    Args:
4533        name: The name to turn into an identifier.
4534        quoted: Whether or not force quote the identifier.
4535
4536    Returns:
4537        The identifier ast node.
4538    """
4539
4540    if name is None:
4541        return None
4542
4543    if isinstance(name, Identifier):
4544        identifier = name
4545    elif isinstance(name, str):
4546        identifier = Identifier(
4547            this=name,
4548            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4549        )
4550    else:
4551        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4552    return identifier
4553
4554
4555INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4556
4557
4558def to_interval(interval: str | Literal) -> Interval:
4559    """Builds an interval expression from a string like '1 day' or '5 months'."""
4560    if isinstance(interval, Literal):
4561        if not interval.is_string:
4562            raise ValueError("Invalid interval string.")
4563
4564        interval = interval.this
4565
4566    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4567
4568    if not interval_parts:
4569        raise ValueError("Invalid interval string.")
4570
4571    return Interval(
4572        this=Literal.string(interval_parts.group(1)),
4573        unit=Var(this=interval_parts.group(2)),
4574    )
4575
4576
4577@t.overload
4578def to_table(sql_path: str | Table, **kwargs) -> Table:
4579    ...
4580
4581
4582@t.overload
4583def to_table(sql_path: None, **kwargs) -> None:
4584    ...
4585
4586
4587def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4588    """
4589    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4590    If a table is passed in then that table is returned.
4591
4592    Args:
4593        sql_path: a `[catalog].[schema].[table]` string.
4594
4595    Returns:
4596        A table expression.
4597    """
4598    if sql_path is None or isinstance(sql_path, Table):
4599        return sql_path
4600    if not isinstance(sql_path, str):
4601        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4602
4603    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4604    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4605
4606
4607def to_column(sql_path: str | Column, **kwargs) -> Column:
4608    """
4609    Create a column from a `[table].[column]` sql path. Schema is optional.
4610
4611    If a column is passed in then that column is returned.
4612
4613    Args:
4614        sql_path: `[table].[column]` string
4615    Returns:
4616        Table: A column expression
4617    """
4618    if sql_path is None or isinstance(sql_path, Column):
4619        return sql_path
4620    if not isinstance(sql_path, str):
4621        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4622    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4623
4624
4625def alias_(
4626    expression: ExpOrStr,
4627    alias: str | Identifier,
4628    table: bool | t.Sequence[str | Identifier] = False,
4629    quoted: t.Optional[bool] = None,
4630    dialect: DialectType = None,
4631    **opts,
4632):
4633    """Create an Alias expression.
4634
4635    Example:
4636        >>> alias_('foo', 'bar').sql()
4637        'foo AS bar'
4638
4639        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4640        '(SELECT 1, 2) AS bar(a, b)'
4641
4642    Args:
4643        expression: the SQL code strings to parse.
4644            If an Expression instance is passed, this is used as-is.
4645        alias: the alias name to use. If the name has
4646            special characters it is quoted.
4647        table: Whether or not to create a table alias, can also be a list of columns.
4648        quoted: whether or not to quote the alias
4649        dialect: the dialect used to parse the input expression.
4650        **opts: other options to use to parse the input expressions.
4651
4652    Returns:
4653        Alias: the aliased expression
4654    """
4655    exp = maybe_parse(expression, dialect=dialect, **opts)
4656    alias = to_identifier(alias, quoted=quoted)
4657
4658    if table:
4659        table_alias = TableAlias(this=alias)
4660        exp.set("alias", table_alias)
4661
4662        if not isinstance(table, bool):
4663            for column in table:
4664                table_alias.append("columns", to_identifier(column, quoted=quoted))
4665
4666        return exp
4667
4668    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4669    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4670    # for the complete Window expression.
4671    #
4672    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4673
4674    if "alias" in exp.arg_types and not isinstance(exp, Window):
4675        exp = exp.copy()
4676        exp.set("alias", alias)
4677        return exp
4678    return Alias(this=exp, alias=alias)
4679
4680
4681def subquery(expression, alias=None, dialect=None, **opts):
4682    """
4683    Build a subquery expression.
4684
4685    Example:
4686        >>> subquery('select x from tbl', 'bar').select('x').sql()
4687        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4688
4689    Args:
4690        expression (str | Expression): the SQL code strings to parse.
4691            If an Expression instance is passed, this is used as-is.
4692        alias (str | Expression): the alias name to use.
4693        dialect (str): the dialect used to parse the input expression.
4694        **opts: other options to use to parse the input expressions.
4695
4696    Returns:
4697        Select: a new select with the subquery expression included
4698    """
4699
4700    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4701    return Select().from_(expression, dialect=dialect, **opts)
4702
4703
4704def column(
4705    col: str | Identifier,
4706    table: t.Optional[str | Identifier] = None,
4707    db: t.Optional[str | Identifier] = None,
4708    catalog: t.Optional[str | Identifier] = None,
4709    quoted: t.Optional[bool] = None,
4710) -> Column:
4711    """
4712    Build a Column.
4713
4714    Args:
4715        col: column name
4716        table: table name
4717        db: db name
4718        catalog: catalog name
4719        quoted: whether or not to force quote each part
4720    Returns:
4721        Column: column instance
4722    """
4723    return Column(
4724        this=to_identifier(col, quoted=quoted),
4725        table=to_identifier(table, quoted=quoted),
4726        db=to_identifier(db, quoted=quoted),
4727        catalog=to_identifier(catalog, quoted=quoted),
4728    )
4729
4730
4731def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4732    """Cast an expression to a data type.
4733
4734    Example:
4735        >>> cast('x + 1', 'int').sql()
4736        'CAST(x + 1 AS INT)'
4737
4738    Args:
4739        expression: The expression to cast.
4740        to: The datatype to cast to.
4741
4742    Returns:
4743        A cast node.
4744    """
4745    expression = maybe_parse(expression, **opts)
4746    return Cast(this=expression, to=DataType.build(to, **opts))
4747
4748
4749def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4750    """Build a Table.
4751
4752    Args:
4753        table (str | Expression): column name
4754        db (str | Expression): db name
4755        catalog (str | Expression): catalog name
4756
4757    Returns:
4758        Table: table instance
4759    """
4760    return Table(
4761        this=to_identifier(table, quoted=quoted),
4762        db=to_identifier(db, quoted=quoted),
4763        catalog=to_identifier(catalog, quoted=quoted),
4764        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4765    )
4766
4767
4768def values(
4769    values: t.Iterable[t.Tuple[t.Any, ...]],
4770    alias: t.Optional[str] = None,
4771    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4772) -> Values:
4773    """Build VALUES statement.
4774
4775    Example:
4776        >>> values([(1, '2')]).sql()
4777        "VALUES (1, '2')"
4778
4779    Args:
4780        values: values statements that will be converted to SQL
4781        alias: optional alias
4782        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4783         If either are provided then an alias is also required.
4784         If a dictionary is provided then the first column of the values will be casted to the expected type
4785         in order to help with type inference.
4786
4787    Returns:
4788        Values: the Values expression object
4789    """
4790    if columns and not alias:
4791        raise ValueError("Alias is required when providing columns")
4792    table_alias = (
4793        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4794        if columns
4795        else TableAlias(this=to_identifier(alias) if alias else None)
4796    )
4797    expressions = [convert(tup) for tup in values]
4798    if columns and isinstance(columns, dict):
4799        types = list(columns.values())
4800        expressions[0].set(
4801            "expressions",
4802            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4803        )
4804    return Values(
4805        expressions=expressions,
4806        alias=table_alias,
4807    )
4808
4809
4810def var(name: t.Optional[ExpOrStr]) -> Var:
4811    """Build a SQL variable.
4812
4813    Example:
4814        >>> repr(var('x'))
4815        '(VAR this: x)'
4816
4817        >>> repr(var(column('x', table='y')))
4818        '(VAR this: x)'
4819
4820    Args:
4821        name: The name of the var or an expression who's name will become the var.
4822
4823    Returns:
4824        The new variable node.
4825    """
4826    if not name:
4827        raise ValueError("Cannot convert empty name into var.")
4828
4829    if isinstance(name, Expression):
4830        name = name.name
4831    return Var(this=name)
4832
4833
4834def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4835    """Build ALTER TABLE... RENAME... expression
4836
4837    Args:
4838        old_name: The old name of the table
4839        new_name: The new name of the table
4840
4841    Returns:
4842        Alter table expression
4843    """
4844    old_table = to_table(old_name)
4845    new_table = to_table(new_name)
4846    return AlterTable(
4847        this=old_table,
4848        actions=[
4849            RenameTable(this=new_table),
4850        ],
4851    )
4852
4853
4854def convert(value) -> Expression:
4855    """Convert a python value into an expression object.
4856
4857    Raises an error if a conversion is not possible.
4858
4859    Args:
4860        value (Any): a python object
4861
4862    Returns:
4863        Expression: the equivalent expression object
4864    """
4865    if isinstance(value, Expression):
4866        return value
4867    if value is None:
4868        return NULL
4869    if isinstance(value, bool):
4870        return Boolean(this=value)
4871    if isinstance(value, str):
4872        return Literal.string(value)
4873    if isinstance(value, float) and math.isnan(value):
4874        return NULL
4875    if isinstance(value, numbers.Number):
4876        return Literal.number(value)
4877    if isinstance(value, tuple):
4878        return Tuple(expressions=[convert(v) for v in value])
4879    if isinstance(value, list):
4880        return Array(expressions=[convert(v) for v in value])
4881    if isinstance(value, dict):
4882        return Map(
4883            keys=[convert(k) for k in value],
4884            values=[convert(v) for v in value.values()],
4885        )
4886    if isinstance(value, datetime.datetime):
4887        datetime_literal = Literal.string(
4888            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4889        )
4890        return TimeStrToTime(this=datetime_literal)
4891    if isinstance(value, datetime.date):
4892        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4893        return DateStrToDate(this=date_literal)
4894    raise ValueError(f"Cannot convert {value}")
4895
4896
4897def replace_children(expression, fun, *args, **kwargs):
4898    """
4899    Replace children of an expression with the result of a lambda fun(child) -> exp.
4900    """
4901    for k, v in expression.args.items():
4902        is_list_arg = type(v) is list
4903
4904        child_nodes = v if is_list_arg else [v]
4905        new_child_nodes = []
4906
4907        for cn in child_nodes:
4908            if isinstance(cn, Expression):
4909                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4910                    new_child_nodes.append(child_node)
4911                    child_node.parent = expression
4912                    child_node.arg_key = k
4913            else:
4914                new_child_nodes.append(cn)
4915
4916        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4917
4918
4919def column_table_names(expression):
4920    """
4921    Return all table names referenced through columns in an expression.
4922
4923    Example:
4924        >>> import sqlglot
4925        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4926        ['c', 'a']
4927
4928    Args:
4929        expression (sqlglot.Expression): expression to find table names
4930
4931    Returns:
4932        list: A list of unique names
4933    """
4934    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4935
4936
4937def table_name(table) -> str:
4938    """Get the full name of a table as a string.
4939
4940    Args:
4941        table (exp.Table | str): table expression node or string.
4942
4943    Examples:
4944        >>> from sqlglot import exp, parse_one
4945        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4946        'a.b.c'
4947
4948    Returns:
4949        The table name.
4950    """
4951
4952    table = maybe_parse(table, into=Table)
4953
4954    if not table:
4955        raise ValueError(f"Cannot parse {table}")
4956
4957    return ".".join(
4958        part
4959        for part in (
4960            table.text("catalog"),
4961            table.text("db"),
4962            table.name,
4963        )
4964        if part
4965    )
4966
4967
4968def replace_tables(expression, mapping):
4969    """Replace all tables in expression according to the mapping.
4970
4971    Args:
4972        expression (sqlglot.Expression): expression node to be transformed and replaced.
4973        mapping (Dict[str, str]): mapping of table names.
4974
4975    Examples:
4976        >>> from sqlglot import exp, parse_one
4977        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4978        'SELECT * FROM c'
4979
4980    Returns:
4981        The mapped expression.
4982    """
4983
4984    def _replace_tables(node):
4985        if isinstance(node, Table):
4986            new_name = mapping.get(table_name(node))
4987            if new_name:
4988                return to_table(
4989                    new_name,
4990                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4991                )
4992        return node
4993
4994    return expression.transform(_replace_tables)
4995
4996
4997def replace_placeholders(expression, *args, **kwargs):
4998    """Replace placeholders in an expression.
4999
5000    Args:
5001        expression (sqlglot.Expression): expression node to be transformed and replaced.
5002        args: positional names that will substitute unnamed placeholders in the given order.
5003        kwargs: keyword arguments that will substitute named placeholders.
5004
5005    Examples:
5006        >>> from sqlglot import exp, parse_one
5007        >>> replace_placeholders(
5008        ...     parse_one("select * from :tbl where ? = ?"),
5009        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5010        ... ).sql()
5011        "SELECT * FROM foo WHERE str_col = 'b'"
5012
5013    Returns:
5014        The mapped expression.
5015    """
5016
5017    def _replace_placeholders(node, args, **kwargs):
5018        if isinstance(node, Placeholder):
5019            if node.name:
5020                new_name = kwargs.get(node.name)
5021                if new_name:
5022                    return convert(new_name)
5023            else:
5024                try:
5025                    return convert(next(args))
5026                except StopIteration:
5027                    pass
5028        return node
5029
5030    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5031
5032
5033def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5034    """Transforms an expression by expanding all referenced sources into subqueries.
5035
5036    Examples:
5037        >>> from sqlglot import parse_one
5038        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5039        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5040
5041    Args:
5042        expression: The expression to expand.
5043        sources: A dictionary of name to Subqueryables.
5044        copy: Whether or not to copy the expression during transformation. Defaults to True.
5045
5046    Returns:
5047        The transformed expression.
5048    """
5049
5050    def _expand(node: Expression):
5051        if isinstance(node, Table):
5052            name = table_name(node)
5053            source = sources.get(name)
5054            if source:
5055                subquery = source.subquery(node.alias or name)
5056                subquery.comments = [f"source: {name}"]
5057                return subquery
5058        return node
5059
5060    return expression.transform(_expand, copy=copy)
5061
5062
5063def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5064    """
5065    Returns a Func expression.
5066
5067    Examples:
5068        >>> func("abs", 5).sql()
5069        'ABS(5)'
5070
5071        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5072        'CAST(5 AS DOUBLE)'
5073
5074    Args:
5075        name: the name of the function to build.
5076        args: the args used to instantiate the function of interest.
5077        dialect: the source dialect.
5078        kwargs: the kwargs used to instantiate the function of interest.
5079
5080    Note:
5081        The arguments `args` and `kwargs` are mutually exclusive.
5082
5083    Returns:
5084        An instance of the function of interest, or an anonymous function, if `name` doesn't
5085        correspond to an existing `sqlglot.expressions.Func` class.
5086    """
5087    if args and kwargs:
5088        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5089
5090    from sqlglot.dialects.dialect import Dialect
5091
5092    converted = [convert(arg) for arg in args]
5093    kwargs = {key: convert(value) for key, value in kwargs.items()}
5094
5095    parser = Dialect.get_or_raise(dialect)().parser()
5096    from_args_list = parser.FUNCTIONS.get(name.upper())
5097
5098    if from_args_list:
5099        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5100    else:
5101        kwargs = kwargs or {"expressions": converted}
5102        function = Anonymous(this=name, **kwargs)
5103
5104    for error_message in function.error_messages(converted):
5105        raise ValueError(error_message)
5106
5107    return function
5108
5109
5110def true():
5111    """
5112    Returns a true Boolean expression.
5113    """
5114    return Boolean(this=True)
5115
5116
5117def false():
5118    """
5119    Returns a false Boolean expression.
5120    """
5121    return Boolean(this=False)
5122
5123
5124def null():
5125    """
5126    Returns a Null expression.
5127    """
5128    return Null()
5129
5130
5131# TODO: deprecate this
5132TRUE = Boolean(this=True)
5133FALSE = Boolean(this=False)
5134NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68
 69    Example:
 70        >>> class Foo(Expression):
 71        ...     arg_types = {"this": True, "expression": False}
 72
 73        The above definition informs us that Foo is an Expression that requires an argument called
 74        "this" and may also optionally receive an argument called "expression".
 75
 76    Args:
 77        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 78        parent: a reference to the parent expression (or None, in case of root expressions).
 79        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 80            uses to refer to it.
 81        comments: a list of comments that are associated with a given expression. This is used in
 82            order to preserve comments when transpiling SQL code.
 83        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 84            optimizer, in order to enable some transformations that require type information.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)
274
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)
285
286    def _set_parent(self, arg_key, value):
287        if hasattr(value, "parent"):
288            value.parent = self
289            value.arg_key = arg_key
290        elif type(value) is list:
291            for v in value:
292                if hasattr(v, "parent"):
293                    v.parent = self
294                    v.arg_key = arg_key
295
296    @property
297    def depth(self):
298        """
299        Returns the depth of this tree.
300        """
301        if self.parent:
302            return self.parent.depth + 1
303        return 0
304
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs
315
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)
328
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression
343
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)
358
359    @property
360    def parent_select(self):
361        """
362        Returns the parent select statement.
363        """
364        return self.find_ancestor(Select)
365
366    @property
367    def same_parent(self):
368        """Returns if the parent is the same class as itself."""
369        return type(self.parent) is self.__class__
370
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression
379
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)
397
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)
413
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))
433
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression
442
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self
450
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())
456
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node
466
467    def __str__(self):
468        return self.sql()
469
470    def __repr__(self):
471        return self._to_s()
472
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)
487
488    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
489        indent = "" if not level else "\n"
490        indent += "".join(["  "] * level)
491        left = f"({self.key.upper()} "
492
493        args: t.Dict[str, t.Any] = {
494            k: ", ".join(
495                v._to_s(hide_missing=hide_missing, level=level + 1)
496                if hasattr(v, "_to_s")
497                else str(v)
498                for v in ensure_list(vs)
499                if v is not None
500            )
501            for k, vs in self.args.items()
502        }
503        args["comments"] = self.comments
504        args["type"] = self.type
505        args = {k: v for k, v in args.items() if v or not hide_missing}
506
507        right = ", ".join(f"{k}: {v}" for k, v in args.items())
508        right += ")"
509
510        return indent + left + right
511
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node
538
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression
565
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self
575
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self
592
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors
626
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)
634
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

def unalias(self):
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "volatile": False,
823        "indexes": False,
824        "no_schema_binding": False,
825        "begin": False,
826    }
class Describe(Expression):
829class Describe(Expression):
830    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
833class Pragma(Expression):
834    pass
class Set(Expression):
837class Set(Expression):
838    arg_types = {"expressions": False}
class SetItem(Expression):
841class SetItem(Expression):
842    arg_types = {
843        "this": False,
844        "expressions": False,
845        "kind": False,
846        "collate": False,  # MySQL SET NAMES statement
847        "global": False,
848    }
class Show(Expression):
851class Show(Expression):
852    arg_types = {
853        "this": True,
854        "target": False,
855        "offset": False,
856        "limit": False,
857        "like": False,
858        "where": False,
859        "db": False,
860        "full": False,
861        "mutex": False,
862        "query": False,
863        "channel": False,
864        "global": False,
865        "log": False,
866        "position": False,
867        "types": False,
868    }
class UserDefinedFunction(Expression):
871class UserDefinedFunction(Expression):
872    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
875class CharacterSet(Expression):
876    arg_types = {"this": True, "default": False}
class With(Expression):
879class With(Expression):
880    arg_types = {"expressions": True, "recursive": False}
881
882    @property
883    def recursive(self) -> bool:
884        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
887class WithinGroup(Expression):
888    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
891class CTE(DerivedTable):
892    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
895class TableAlias(Expression):
896    arg_types = {"this": False, "columns": False}
897
898    @property
899    def columns(self):
900        return self.args.get("columns") or []
class BitString(Condition):
903class BitString(Condition):
904    pass
class HexString(Condition):
907class HexString(Condition):
908    pass
class ByteString(Condition):
911class ByteString(Condition):
912    pass
class Column(Condition):
915class Column(Condition):
916    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
917
918    @property
919    def table(self) -> str:
920        return self.text("table")
921
922    @property
923    def db(self) -> str:
924        return self.text("db")
925
926    @property
927    def catalog(self) -> str:
928        return self.text("catalog")
929
930    @property
931    def output_name(self) -> str:
932        return self.name
933
934    @property
935    def parts(self) -> t.List[Identifier]:
936        """Return the parts of a column in order catalog, db, table, name."""
937        return [part for part in reversed(list(self.args.values())) if part]
938
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
952class ColumnPosition(Expression):
953    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
956class ColumnDef(Expression):
957    arg_types = {
958        "this": True,
959        "kind": False,
960        "constraints": False,
961        "exists": False,
962        "position": False,
963    }
class AlterColumn(Expression):
966class AlterColumn(Expression):
967    arg_types = {
968        "this": True,
969        "dtype": False,
970        "collate": False,
971        "using": False,
972        "default": False,
973        "drop": False,
974    }
class RenameTable(Expression):
977class RenameTable(Expression):
978    pass
class SetTag(Expression):
981class SetTag(Expression):
982    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
985class Comment(Expression):
986    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
989class ColumnConstraint(Expression):
990    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
993class ColumnConstraintKind(Expression):
994    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
997class AutoIncrementColumnConstraint(ColumnConstraintKind):
998    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001class CaseSpecificColumnConstraint(ColumnConstraintKind):
1002    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1005class CharacterSetColumnConstraint(ColumnConstraintKind):
1006    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1009class CheckColumnConstraint(ColumnConstraintKind):
1010    pass
class CollateColumnConstraint(ColumnConstraintKind):
1013class CollateColumnConstraint(ColumnConstraintKind):
1014    pass
class CommentColumnConstraint(ColumnConstraintKind):
1017class CommentColumnConstraint(ColumnConstraintKind):
1018    pass
class CompressColumnConstraint(ColumnConstraintKind):
1021class CompressColumnConstraint(ColumnConstraintKind):
1022    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1025class DateFormatColumnConstraint(ColumnConstraintKind):
1026    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1029class DefaultColumnConstraint(ColumnConstraintKind):
1030    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1033class EncodeColumnConstraint(ColumnConstraintKind):
1034    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1038    # this: True -> ALWAYS, this: False -> BY DEFAULT
1039    arg_types = {
1040        "this": False,
1041        "start": False,
1042        "increment": False,
1043        "minvalue": False,
1044        "maxvalue": False,
1045        "cycle": False,
1046    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1049class InlineLengthColumnConstraint(ColumnConstraintKind):
1050    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1053class NotNullColumnConstraint(ColumnConstraintKind):
1054    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1057class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1058    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1061class TitleColumnConstraint(ColumnConstraintKind):
1062    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1065class UniqueColumnConstraint(ColumnConstraintKind):
1066    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1069class UppercaseColumnConstraint(ColumnConstraintKind):
1070    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1073class PathColumnConstraint(ColumnConstraintKind):
1074    pass
class Constraint(Expression):
1077class Constraint(Expression):
1078    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1081class Delete(Expression):
1082    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1083
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )
1116
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )
1155
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1192class Drop(Expression):
1193    arg_types = {
1194        "this": False,
1195        "kind": False,
1196        "exists": False,
1197        "temporary": False,
1198        "materialized": False,
1199        "cascade": False,
1200        "constraints": False,
1201    }
class Filter(Expression):
1204class Filter(Expression):
1205    arg_types = {"this": True, "expression": True}
class Check(Expression):
1208class Check(Expression):
1209    pass
class Directory(Expression):
1212class Directory(Expression):
1213    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1214    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1217class ForeignKey(Expression):
1218    arg_types = {
1219        "expressions": True,
1220        "reference": False,
1221        "delete": False,
1222        "update": False,
1223    }
class PrimaryKey(Expression):
1226class PrimaryKey(Expression):
1227    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1230class Unique(Expression):
1231    arg_types = {"expressions": True}
class Into(Expression):
1236class Into(Expression):
1237    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1240class From(Expression):
1241    arg_types = {"expressions": True}
class Having(Expression):
1244class Having(Expression):
1245    pass
class Hint(Expression):
1248class Hint(Expression):
1249    arg_types = {"expressions": True}
class JoinHint(Expression):
1252class JoinHint(Expression):
1253    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1256class Identifier(Expression):
1257    arg_types = {"this": True, "quoted": False}
1258
1259    @property
1260    def quoted(self):
1261        return bool(self.args.get("quoted"))
1262
1263    @property
1264    def hashable_args(self) -> t.Any:
1265        if self.quoted and any(char.isupper() for char in self.this):
1266            return (self.this, self.quoted)
1267        return self.this.lower()
1268
1269    @property
1270    def output_name(self):
1271        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1274class Index(Expression):
1275    arg_types = {
1276        "this": False,
1277        "table": False,
1278        "where": False,
1279        "columns": False,
1280        "unique": False,
1281        "primary": False,
1282        "amp": False,  # teradata
1283    }
class Insert(Expression):
1286class Insert(Expression):
1287    arg_types = {
1288        "with": False,
1289        "this": True,
1290        "expression": False,
1291        "returning": False,
1292        "overwrite": False,
1293        "exists": False,
1294        "partition": False,
1295        "alternative": False,
1296    }
class Returning(Expression):
1299class Returning(Expression):
1300    arg_types = {"expressions": True}
class Introducer(Expression):
1304class Introducer(Expression):
1305    arg_types = {"this": True, "expression": True}
class National(Expression):
1309class National(Expression):
1310    pass
class LoadData(Expression):
1313class LoadData(Expression):
1314    arg_types = {
1315        "this": True,
1316        "local": False,
1317        "overwrite": False,
1318        "inpath": True,
1319        "partition": False,
1320        "input_format": False,
1321        "serde": False,
1322    }
class Partition(Expression):
1325class Partition(Expression):
1326    arg_types = {"expressions": True}
class Fetch(Expression):
1329class Fetch(Expression):
1330    arg_types = {"direction": False, "count": False}
class Group(Expression):
1333class Group(Expression):
1334    arg_types = {
1335        "expressions": False,
1336        "grouping_sets": False,
1337        "cube": False,
1338        "rollup": False,
1339    }
class Lambda(Expression):
1342class Lambda(Expression):
1343    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1346class Limit(Expression):
1347    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1350class Literal(Condition):
1351    arg_types = {"this": True, "is_string": True}
1352
1353    @property
1354    def hashable_args(self) -> t.Any:
1355        return (self.this, self.args.get("is_string"))
1356
1357    @classmethod
1358    def number(cls, number) -> Literal:
1359        return cls(this=str(number), is_string=False)
1360
1361    @classmethod
1362    def string(cls, string) -> Literal:
1363        return cls(this=str(string), is_string=True)
1364
1365    @property
1366    def output_name(self):
1367        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1357    @classmethod
1358    def number(cls, number) -> Literal:
1359        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1361    @classmethod
1362    def string(cls, string) -> Literal:
1363        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1370class Join(Expression):
1371    arg_types = {
1372        "this": True,
1373        "on": False,
1374        "side": False,
1375        "kind": False,
1376        "using": False,
1377        "natural": False,
1378    }
1379
1380    @property
1381    def kind(self):
1382        return self.text("kind").upper()
1383
1384    @property
1385    def side(self):
1386        return self.text("side").upper()
1387
1388    @property
1389    def alias_or_name(self):
1390        return self.this.alias_or_name
1391
1392    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the ON expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1399            'JOIN x ON y = 1'
1400
1401        Args:
1402            *expressions (str | Expression): the SQL code strings to parse.
1403                If an `Expression` instance is passed, it will be used as-is.
1404                Multiple expressions are combined with an AND operator.
1405            append (bool): if `True`, AND the new expressions to any existing expression.
1406                Otherwise, this resets the expression.
1407            dialect (str): the dialect used to parse the input expressions.
1408            copy (bool): if `False`, modify this expression instance in-place.
1409            opts (kwargs): other options to use to parse the input expressions.
1410
1411        Returns:
1412            Join: the modified join expression.
1413        """
1414        join = _apply_conjunction_builder(
1415            *expressions,
1416            instance=self,
1417            arg="on",
1418            append=append,
1419            dialect=dialect,
1420            copy=copy,
1421            **opts,
1422        )
1423
1424        if join.kind == "CROSS":
1425            join.set("kind", None)
1426
1427        return join
1428
1429    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430        """
1431        Append to or set the USING expressions.
1432
1433        Example:
1434            >>> import sqlglot
1435            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1436            'JOIN x USING (foo, bla)'
1437
1438        Args:
1439            *expressions (str | Expression): the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1442                Otherwise, this resets the expression.
1443            dialect (str): the dialect used to parse the input expressions.
1444            copy (bool): if `False`, modify this expression instance in-place.
1445            opts (kwargs): other options to use to parse the input expressions.
1446
1447        Returns:
1448            Join: the modified join expression.
1449        """
1450        join = _apply_list_builder(
1451            *expressions,
1452            instance=self,
1453            arg="using",
1454            append=append,
1455            dialect=dialect,
1456            copy=copy,
1457            **opts,
1458        )
1459
1460        if join.kind == "CROSS":
1461            join.set("kind", None)
1462
1463        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1392    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the ON expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1399            'JOIN x ON y = 1'
1400
1401        Args:
1402            *expressions (str | Expression): the SQL code strings to parse.
1403                If an `Expression` instance is passed, it will be used as-is.
1404                Multiple expressions are combined with an AND operator.
1405            append (bool): if `True`, AND the new expressions to any existing expression.
1406                Otherwise, this resets the expression.
1407            dialect (str): the dialect used to parse the input expressions.
1408            copy (bool): if `False`, modify this expression instance in-place.
1409            opts (kwargs): other options to use to parse the input expressions.
1410
1411        Returns:
1412            Join: the modified join expression.
1413        """
1414        join = _apply_conjunction_builder(
1415            *expressions,
1416            instance=self,
1417            arg="on",
1418            append=append,
1419            dialect=dialect,
1420            copy=copy,
1421            **opts,
1422        )
1423
1424        if join.kind == "CROSS":
1425            join.set("kind", None)
1426
1427        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1429    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430        """
1431        Append to or set the USING expressions.
1432
1433        Example:
1434            >>> import sqlglot
1435            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1436            'JOIN x USING (foo, bla)'
1437
1438        Args:
1439            *expressions (str | Expression): the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1442                Otherwise, this resets the expression.
1443            dialect (str): the dialect used to parse the input expressions.
1444            copy (bool): if `False`, modify this expression instance in-place.
1445            opts (kwargs): other options to use to parse the input expressions.
1446
1447        Returns:
1448            Join: the modified join expression.
1449        """
1450        join = _apply_list_builder(
1451            *expressions,
1452            instance=self,
1453            arg="using",
1454            append=append,
1455            dialect=dialect,
1456            copy=copy,
1457            **opts,
1458        )
1459
1460        if join.kind == "CROSS":
1461            join.set("kind", None)
1462
1463        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1466class Lateral(UDTF):
1467    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1470class MatchRecognize(Expression):
1471    arg_types = {
1472        "partition_by": False,
1473        "order": False,
1474        "measures": False,
1475        "rows": False,
1476        "after": False,
1477        "pattern": False,
1478        "define": False,
1479    }
class Final(Expression):
1484class Final(Expression):
1485    pass
class Offset(Expression):
1488class Offset(Expression):
1489    arg_types = {"this": False, "expression": True}
class Order(Expression):
1492class Order(Expression):
1493    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1498class Cluster(Order):
1499    pass
class Distribute(Order):
1502class Distribute(Order):
1503    pass
class Sort(Order):
1506class Sort(Order):
1507    pass
class Ordered(Expression):
1510class Ordered(Expression):
1511    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1514class Property(Expression):
1515    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1518class AfterJournalProperty(Property):
1519    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1522class AlgorithmProperty(Property):
1523    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1526class AutoIncrementProperty(Property):
1527    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1530class BlockCompressionProperty(Property):
1531    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1534class CharacterSetProperty(Property):
1535    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1538class ChecksumProperty(Property):
1539    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1542class CollateProperty(Property):
1543    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1546class DataBlocksizeProperty(Property):
1547    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1550class DefinerProperty(Property):
1551    arg_types = {"this": True}
class DistKeyProperty(Property):
1554class DistKeyProperty(Property):
1555    arg_types = {"this": True}
class DistStyleProperty(Property):
1558class DistStyleProperty(Property):
1559    arg_types = {"this": True}
class EngineProperty(Property):
1562class EngineProperty(Property):
1563    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1566class ExecuteAsProperty(Property):
1567    arg_types = {"this": True}
class ExternalProperty(Property):
1570class ExternalProperty(Property):
1571    arg_types = {"this": False}
class FallbackProperty(Property):
1574class FallbackProperty(Property):
1575    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1578class FileFormatProperty(Property):
1579    arg_types = {"this": True}
class FreespaceProperty(Property):
1582class FreespaceProperty(Property):
1583    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1586class IsolatedLoadingProperty(Property):
1587    arg_types = {
1588        "no": True,
1589        "concurrent": True,
1590        "for_all": True,
1591        "for_insert": True,
1592        "for_none": True,
1593    }
class JournalProperty(Property):
1596class JournalProperty(Property):
1597    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1600class LanguageProperty(Property):
1601    arg_types = {"this": True}
class LikeProperty(Property):
1604class LikeProperty(Property):
1605    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1608class LocationProperty(Property):
1609    arg_types = {"this": True}
class LockingProperty(Property):
1612class LockingProperty(Property):
1613    arg_types = {
1614        "this": False,
1615        "kind": True,
1616        "for_or_in": True,
1617        "lock_type": True,
1618        "override": False,
1619    }
class LogProperty(Property):
1622class LogProperty(Property):
1623    arg_types = {"no": True}
class MaterializedProperty(Property):
1626class MaterializedProperty(Property):
1627    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1630class MergeBlockRatioProperty(Property):
1631    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1634class NoPrimaryIndexProperty(Property):
1635    arg_types = {"this": False}
class OnCommitProperty(Property):
1638class OnCommitProperty(Property):
1639    arg_type = {"this": False}
class PartitionedByProperty(Property):
1642class PartitionedByProperty(Property):
1643    arg_types = {"this": True}
class ReturnsProperty(Property):
1646class ReturnsProperty(Property):
1647    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1650class RowFormatDelimitedProperty(Property):
1651    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1652    arg_types = {
1653        "fields": False,
1654        "escaped": False,
1655        "collection_items": False,
1656        "map_keys": False,
1657        "lines": False,
1658        "null": False,
1659        "serde": False,
1660    }
class RowFormatSerdeProperty(Property):
1663class RowFormatSerdeProperty(Property):
1664    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1667class SchemaCommentProperty(Property):
1668    arg_types = {"this": True}
class SerdeProperties(Property):
1671class SerdeProperties(Property):
1672    arg_types = {"expressions": True}
class SetProperty(Property):
1675class SetProperty(Property):
1676    arg_types = {"multi": True}
class SortKeyProperty(Property):
1679class SortKeyProperty(Property):
1680    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1683class SqlSecurityProperty(Property):
1684    arg_types = {"definer": True}
class TableFormatProperty(Property):
1687class TableFormatProperty(Property):
1688    arg_types = {"this": True}
class TemporaryProperty(Property):
1691class TemporaryProperty(Property):
1692    arg_types = {"global_": True}
class TransientProperty(Property):
1695class TransientProperty(Property):
1696    arg_types = {"this": False}
class VolatilityProperty(Property):
1699class VolatilityProperty(Property):
1700    arg_types = {"this": True}
class WithDataProperty(Property):
1703class WithDataProperty(Property):
1704    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1707class WithJournalTableProperty(Property):
1708    arg_types = {"this": True}
class Properties(Expression):
1711class Properties(Expression):
1712    arg_types = {"expressions": True}
1713
1714    NAME_TO_PROPERTY = {
1715        "ALGORITHM": AlgorithmProperty,
1716        "AUTO_INCREMENT": AutoIncrementProperty,
1717        "CHARACTER SET": CharacterSetProperty,
1718        "COLLATE": CollateProperty,
1719        "COMMENT": SchemaCommentProperty,
1720        "DEFINER": DefinerProperty,
1721        "DISTKEY": DistKeyProperty,
1722        "DISTSTYLE": DistStyleProperty,
1723        "ENGINE": EngineProperty,
1724        "EXECUTE AS": ExecuteAsProperty,
1725        "FORMAT": FileFormatProperty,
1726        "LANGUAGE": LanguageProperty,
1727        "LOCATION": LocationProperty,
1728        "PARTITIONED_BY": PartitionedByProperty,
1729        "RETURNS": ReturnsProperty,
1730        "SORTKEY": SortKeyProperty,
1731        "TABLE_FORMAT": TableFormatProperty,
1732    }
1733
1734    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1735
1736    # CREATE property locations
1737    # Form: schema specified
1738    #   create [POST_CREATE]
1739    #     table a [POST_NAME]
1740    #     (b int) [POST_SCHEMA]
1741    #     with ([POST_WITH])
1742    #     index (b) [POST_INDEX]
1743    #
1744    # Form: alias selection
1745    #   create [POST_CREATE]
1746    #     table a [POST_NAME]
1747    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1748    #     index (c) [POST_INDEX]
1749    class Location(AutoName):
1750        POST_CREATE = auto()
1751        POST_NAME = auto()
1752        POST_SCHEMA = auto()
1753        POST_WITH = auto()
1754        POST_ALIAS = auto()
1755        POST_EXPRESSION = auto()
1756        POST_INDEX = auto()
1757        UNSUPPORTED = auto()
1758
1759    @classmethod
1760    def from_dict(cls, properties_dict) -> Properties:
1761        expressions = []
1762        for key, value in properties_dict.items():
1763            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1764            if property_cls:
1765                expressions.append(property_cls(this=convert(value)))
1766            else:
1767                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1768
1769        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1759    @classmethod
1760    def from_dict(cls, properties_dict) -> Properties:
1761        expressions = []
1762        for key, value in properties_dict.items():
1763            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1764            if property_cls:
1765                expressions.append(property_cls(this=convert(value)))
1766            else:
1767                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1768
1769        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1749    class Location(AutoName):
1750        POST_CREATE = auto()
1751        POST_NAME = auto()
1752        POST_SCHEMA = auto()
1753        POST_WITH = auto()
1754        POST_ALIAS = auto()
1755        POST_EXPRESSION = auto()
1756        POST_INDEX = auto()
1757        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1772class Qualify(Expression):
1773    pass
class Return(Expression):
1777class Return(Expression):
1778    pass
class Reference(Expression):
1781class Reference(Expression):
1782    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1785class Tuple(Expression):
1786    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1789class Subqueryable(Unionable):
1790    def subquery(self, alias=None, copy=True) -> Subquery:
1791        """
1792        Convert this expression to an aliased expression that can be used as a Subquery.
1793
1794        Example:
1795            >>> subquery = Select().select("x").from_("tbl").subquery()
1796            >>> Select().select("x").from_(subquery).sql()
1797            'SELECT x FROM (SELECT x FROM tbl)'
1798
1799        Args:
1800            alias (str | Identifier): an optional alias for the subquery
1801            copy (bool): if `False`, modify this expression instance in-place.
1802
1803        Returns:
1804            Alias: the subquery
1805        """
1806        instance = _maybe_copy(self, copy)
1807        return Subquery(
1808            this=instance,
1809            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1810        )
1811
1812    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1813        raise NotImplementedError
1814
1815    @property
1816    def ctes(self):
1817        with_ = self.args.get("with")
1818        if not with_:
1819            return []
1820        return with_.expressions
1821
1822    @property
1823    def selects(self):
1824        raise NotImplementedError("Subqueryable objects must implement `selects`")
1825
1826    @property
1827    def named_selects(self):
1828        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1829
1830    def with_(
1831        self,
1832        alias,
1833        as_,
1834        recursive=None,
1835        append=True,
1836        dialect=None,
1837        copy=True,
1838        **opts,
1839    ):
1840        """
1841        Append to or set the common table expressions.
1842
1843        Example:
1844            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1845            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1846
1847        Args:
1848            alias (str | Expression): the SQL code string to parse as the table name.
1849                If an `Expression` instance is passed, this is used as-is.
1850            as_ (str | Expression): the SQL code string to parse as the table expression.
1851                If an `Expression` instance is passed, it will be used as-is.
1852            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1853            append (bool): if `True`, add to any existing expressions.
1854                Otherwise, this resets the expressions.
1855            dialect (str): the dialect used to parse the input expression.
1856            copy (bool): if `False`, modify this expression instance in-place.
1857            opts (kwargs): other options to use to parse the input expressions.
1858
1859        Returns:
1860            Select: the modified expression.
1861        """
1862        alias_expression = maybe_parse(
1863            alias,
1864            dialect=dialect,
1865            into=TableAlias,
1866            **opts,
1867        )
1868        as_expression = maybe_parse(
1869            as_,
1870            dialect=dialect,
1871            **opts,
1872        )
1873        cte = CTE(
1874            this=as_expression,
1875            alias=alias_expression,
1876        )
1877        return _apply_child_list_builder(
1878            cte,
1879            instance=self,
1880            arg="with",
1881            append=append,
1882            copy=copy,
1883            into=With,
1884            properties={"recursive": recursive or False},
1885        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1790    def subquery(self, alias=None, copy=True) -> Subquery:
1791        """
1792        Convert this expression to an aliased expression that can be used as a Subquery.
1793
1794        Example:
1795            >>> subquery = Select().select("x").from_("tbl").subquery()
1796            >>> Select().select("x").from_(subquery).sql()
1797            'SELECT x FROM (SELECT x FROM tbl)'
1798
1799        Args:
1800            alias (str | Identifier): an optional alias for the subquery
1801            copy (bool): if `False`, modify this expression instance in-place.
1802
1803        Returns:
1804            Alias: the subquery
1805        """
1806        instance = _maybe_copy(self, copy)
1807        return Subquery(
1808            this=instance,
1809            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1810        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1812    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1813        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1830    def with_(
1831        self,
1832        alias,
1833        as_,
1834        recursive=None,
1835        append=True,
1836        dialect=None,
1837        copy=True,
1838        **opts,
1839    ):
1840        """
1841        Append to or set the common table expressions.
1842
1843        Example:
1844            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1845            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1846
1847        Args:
1848            alias (str | Expression): the SQL code string to parse as the table name.
1849                If an `Expression` instance is passed, this is used as-is.
1850            as_ (str | Expression): the SQL code string to parse as the table expression.
1851                If an `Expression` instance is passed, it will be used as-is.
1852            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1853            append (bool): if `True`, add to any existing expressions.
1854                Otherwise, this resets the expressions.
1855            dialect (str): the dialect used to parse the input expression.
1856            copy (bool): if `False`, modify this expression instance in-place.
1857            opts (kwargs): other options to use to parse the input expressions.
1858
1859        Returns:
1860            Select: the modified expression.
1861        """
1862        alias_expression = maybe_parse(
1863            alias,
1864            dialect=dialect,
1865            into=TableAlias,
1866            **opts,
1867        )
1868        as_expression = maybe_parse(
1869            as_,
1870            dialect=dialect,
1871            **opts,
1872        )
1873        cte = CTE(
1874            this=as_expression,
1875            alias=alias_expression,
1876        )
1877        return _apply_child_list_builder(
1878            cte,
1879            instance=self,
1880            arg="with",
1881            append=append,
1882            copy=copy,
1883            into=With,
1884            properties={"recursive": recursive or False},
1885        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1909class Table(Expression):
1910    arg_types = {
1911        "this": True,
1912        "alias": False,
1913        "db": False,
1914        "catalog": False,
1915        "laterals": False,
1916        "joins": False,
1917        "pivots": False,
1918        "hints": False,
1919        "system_time": False,
1920    }
1921
1922    @property
1923    def db(self) -> str:
1924        return self.text("db")
1925
1926    @property
1927    def catalog(self) -> str:
1928        return self.text("catalog")
class SystemTime(Expression):
1932class SystemTime(Expression):
1933    arg_types = {
1934        "this": False,
1935        "expression": False,
1936        "kind": True,
1937    }
class Union(Subqueryable):
1940class Union(Subqueryable):
1941    arg_types = {
1942        "with": False,
1943        "this": True,
1944        "expression": True,
1945        "distinct": False,
1946        **QUERY_MODIFIERS,
1947    }
1948
1949    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1950        """
1951        Set the LIMIT expression.
1952
1953        Example:
1954            >>> select("1").union(select("1")).limit(1).sql()
1955            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1956
1957        Args:
1958            expression (str | int | Expression): the SQL code string to parse.
1959                This can also be an integer.
1960                If a `Limit` instance is passed, this is used as-is.
1961                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1962            dialect (str): the dialect used to parse the input expression.
1963            copy (bool): if `False`, modify this expression instance in-place.
1964            opts (kwargs): other options to use to parse the input expressions.
1965
1966        Returns:
1967            Select: The limited subqueryable.
1968        """
1969        return (
1970            select("*")
1971            .from_(self.subquery(alias="_l_0", copy=copy))
1972            .limit(expression, dialect=dialect, copy=False, **opts)
1973        )
1974
1975    def select(
1976        self,
1977        *expressions: ExpOrStr,
1978        append: bool = True,
1979        dialect: DialectType = None,
1980        copy: bool = True,
1981        **opts,
1982    ) -> Union:
1983        """Append to or set the SELECT of the union recursively.
1984
1985        Example:
1986            >>> from sqlglot import parse_one
1987            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1988            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1989
1990        Args:
1991            *expressions: the SQL code strings to parse.
1992                If an `Expression` instance is passed, it will be used as-is.
1993            append: if `True`, add to any existing expressions.
1994                Otherwise, this resets the expressions.
1995            dialect: the dialect used to parse the input expressions.
1996            copy: if `False`, modify this expression instance in-place.
1997            opts: other options to use to parse the input expressions.
1998
1999        Returns:
2000            Union: the modified expression.
2001        """
2002        this = self.copy() if copy else self
2003        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2004        this.expression.unnest().select(
2005            *expressions, append=append, dialect=dialect, copy=False, **opts
2006        )
2007        return this
2008
2009    @property
2010    def named_selects(self):
2011        return self.this.unnest().named_selects
2012
2013    @property
2014    def is_star(self) -> bool:
2015        return self.this.is_star or self.expression.is_star
2016
2017    @property
2018    def selects(self):
2019        return self.this.unnest().selects
2020
2021    @property
2022    def left(self):
2023        return self.this
2024
2025    @property
2026    def right(self):
2027        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1949    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1950        """
1951        Set the LIMIT expression.
1952
1953        Example:
1954            >>> select("1").union(select("1")).limit(1).sql()
1955            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1956
1957        Args:
1958            expression (str | int | Expression): the SQL code string to parse.
1959                This can also be an integer.
1960                If a `Limit` instance is passed, this is used as-is.
1961                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1962            dialect (str): the dialect used to parse the input expression.
1963            copy (bool): if `False`, modify this expression instance in-place.
1964            opts (kwargs): other options to use to parse the input expressions.
1965
1966        Returns:
1967            Select: The limited subqueryable.
1968        """
1969        return (
1970            select("*")
1971            .from_(self.subquery(alias="_l_0", copy=copy))
1972            .limit(expression, dialect=dialect, copy=False, **opts)
1973        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1975    def select(
1976        self,
1977        *expressions: ExpOrStr,
1978        append: bool = True,
1979        dialect: DialectType = None,
1980        copy: bool = True,
1981        **opts,
1982    ) -> Union:
1983        """Append to or set the SELECT of the union recursively.
1984
1985        Example:
1986            >>> from sqlglot import parse_one
1987            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1988            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1989
1990        Args:
1991            *expressions: the SQL code strings to parse.
1992                If an `Expression` instance is passed, it will be used as-is.
1993            append: if `True`, add to any existing expressions.
1994                Otherwise, this resets the expressions.
1995            dialect: the dialect used to parse the input expressions.
1996            copy: if `False`, modify this expression instance in-place.
1997            opts: other options to use to parse the input expressions.
1998
1999        Returns:
2000            Union: the modified expression.
2001        """
2002        this = self.copy() if copy else self
2003        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2004        this.expression.unnest().select(
2005            *expressions, append=append, dialect=dialect, copy=False, **opts
2006        )
2007        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2030class Except(Union):
2031    pass
class Intersect(Union):
2034class Intersect(Union):
2035    pass
class Unnest(UDTF):
2038class Unnest(UDTF):
2039    arg_types = {
2040        "expressions": True,
2041        "ordinality": False,
2042        "alias": False,
2043        "offset": False,
2044    }
class Update(Expression):
2047class Update(Expression):
2048    arg_types = {
2049        "with": False,
2050        "this": False,
2051        "expressions": True,
2052        "from": False,
2053        "where": False,
2054        "returning": False,
2055    }
class Values(UDTF):
2058class Values(UDTF):
2059    arg_types = {
2060        "expressions": True,
2061        "ordinality": False,
2062        "alias": False,
2063    }
class Var(Expression):
2066class Var(Expression):
2067    pass
class Schema(Expression):
2070class Schema(Expression):
2071    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2076class Lock(Expression):
2077    arg_types = {"update": True}
class Select(Subqueryable):
2080class Select(Subqueryable):
2081    arg_types = {
2082        "with": False,
2083        "kind": False,
2084        "expressions": False,
2085        "hint": False,
2086        "distinct": False,
2087        "into": False,
2088        "from": False,
2089        **QUERY_MODIFIERS,
2090    }
2091
2092    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2093        """
2094        Set the FROM expression.
2095
2096        Example:
2097            >>> Select().from_("tbl").select("x").sql()
2098            'SELECT x FROM tbl'
2099
2100        Args:
2101            *expressions (str | Expression): the SQL code strings to parse.
2102                If a `From` instance is passed, this is used as-is.
2103                If another `Expression` instance is passed, it will be wrapped in a `From`.
2104            append (bool): if `True`, add to any existing expressions.
2105                Otherwise, this flattens all the `From` expression into a single expression.
2106            dialect (str): the dialect used to parse the input expression.
2107            copy (bool): if `False`, modify this expression instance in-place.
2108            opts (kwargs): other options to use to parse the input expressions.
2109
2110        Returns:
2111            Select: the modified expression.
2112        """
2113        return _apply_child_list_builder(
2114            *expressions,
2115            instance=self,
2116            arg="from",
2117            append=append,
2118            copy=copy,
2119            prefix="FROM",
2120            into=From,
2121            dialect=dialect,
2122            **opts,
2123        )
2124
2125    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2126        """
2127        Set the GROUP BY expression.
2128
2129        Example:
2130            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2131            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2132
2133        Args:
2134            *expressions (str | Expression): the SQL code strings to parse.
2135                If a `Group` instance is passed, this is used as-is.
2136                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2137                If nothing is passed in then a group by is not applied to the expression
2138            append (bool): if `True`, add to any existing expressions.
2139                Otherwise, this flattens all the `Group` expression into a single expression.
2140            dialect (str): the dialect used to parse the input expression.
2141            copy (bool): if `False`, modify this expression instance in-place.
2142            opts (kwargs): other options to use to parse the input expressions.
2143
2144        Returns:
2145            Select: the modified expression.
2146        """
2147        if not expressions:
2148            return self if not copy else self.copy()
2149        return _apply_child_list_builder(
2150            *expressions,
2151            instance=self,
2152            arg="group",
2153            append=append,
2154            copy=copy,
2155            prefix="GROUP BY",
2156            into=Group,
2157            dialect=dialect,
2158            **opts,
2159        )
2160
2161    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2162        """
2163        Set the ORDER BY expression.
2164
2165        Example:
2166            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2167            'SELECT x FROM tbl ORDER BY x DESC'
2168
2169        Args:
2170            *expressions (str | Expression): the SQL code strings to parse.
2171                If a `Group` instance is passed, this is used as-is.
2172                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2173            append (bool): if `True`, add to any existing expressions.
2174                Otherwise, this flattens all the `Order` expression into a single expression.
2175            dialect (str): the dialect used to parse the input expression.
2176            copy (bool): if `False`, modify this expression instance in-place.
2177            opts (kwargs): other options to use to parse the input expressions.
2178
2179        Returns:
2180            Select: the modified expression.
2181        """
2182        return _apply_child_list_builder(
2183            *expressions,
2184            instance=self,
2185            arg="order",
2186            append=append,
2187            copy=copy,
2188            prefix="ORDER BY",
2189            into=Order,
2190            dialect=dialect,
2191            **opts,
2192        )
2193
2194    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2195        """
2196        Set the SORT BY expression.
2197
2198        Example:
2199            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2200            'SELECT x FROM tbl SORT BY x DESC'
2201
2202        Args:
2203            *expressions (str | Expression): the SQL code strings to parse.
2204                If a `Group` instance is passed, this is used as-is.
2205                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2206            append (bool): if `True`, add to any existing expressions.
2207                Otherwise, this flattens all the `Order` expression into a single expression.
2208            dialect (str): the dialect used to parse the input expression.
2209            copy (bool): if `False`, modify this expression instance in-place.
2210            opts (kwargs): other options to use to parse the input expressions.
2211
2212        Returns:
2213            Select: the modified expression.
2214        """
2215        return _apply_child_list_builder(
2216            *expressions,
2217            instance=self,
2218            arg="sort",
2219            append=append,
2220            copy=copy,
2221            prefix="SORT BY",
2222            into=Sort,
2223            dialect=dialect,
2224            **opts,
2225        )
2226
2227    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2228        """
2229        Set the CLUSTER BY expression.
2230
2231        Example:
2232            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2233            'SELECT x FROM tbl CLUSTER BY x DESC'
2234
2235        Args:
2236            *expressions (str | Expression): the SQL code strings to parse.
2237                If a `Group` instance is passed, this is used as-is.
2238                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2239            append (bool): if `True`, add to any existing expressions.
2240                Otherwise, this flattens all the `Order` expression into a single expression.
2241            dialect (str): the dialect used to parse the input expression.
2242            copy (bool): if `False`, modify this expression instance in-place.
2243            opts (kwargs): other options to use to parse the input expressions.
2244
2245        Returns:
2246            Select: the modified expression.
2247        """
2248        return _apply_child_list_builder(
2249            *expressions,
2250            instance=self,
2251            arg="cluster",
2252            append=append,
2253            copy=copy,
2254            prefix="CLUSTER BY",
2255            into=Cluster,
2256            dialect=dialect,
2257            **opts,
2258        )
2259
2260    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2261        """
2262        Set the LIMIT expression.
2263
2264        Example:
2265            >>> Select().from_("tbl").select("x").limit(10).sql()
2266            'SELECT x FROM tbl LIMIT 10'
2267
2268        Args:
2269            expression (str | int | Expression): the SQL code string to parse.
2270                This can also be an integer.
2271                If a `Limit` instance is passed, this is used as-is.
2272                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2273            dialect (str): the dialect used to parse the input expression.
2274            copy (bool): if `False`, modify this expression instance in-place.
2275            opts (kwargs): other options to use to parse the input expressions.
2276
2277        Returns:
2278            Select: the modified expression.
2279        """
2280        return _apply_builder(
2281            expression=expression,
2282            instance=self,
2283            arg="limit",
2284            into=Limit,
2285            prefix="LIMIT",
2286            dialect=dialect,
2287            copy=copy,
2288            **opts,
2289        )
2290
2291    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2292        """
2293        Set the OFFSET expression.
2294
2295        Example:
2296            >>> Select().from_("tbl").select("x").offset(10).sql()
2297            'SELECT x FROM tbl OFFSET 10'
2298
2299        Args:
2300            expression (str | int | Expression): the SQL code string to parse.
2301                This can also be an integer.
2302                If a `Offset` instance is passed, this is used as-is.
2303                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2304            dialect (str): the dialect used to parse the input expression.
2305            copy (bool): if `False`, modify this expression instance in-place.
2306            opts (kwargs): other options to use to parse the input expressions.
2307
2308        Returns:
2309            Select: the modified expression.
2310        """
2311        return _apply_builder(
2312            expression=expression,
2313            instance=self,
2314            arg="offset",
2315            into=Offset,
2316            prefix="OFFSET",
2317            dialect=dialect,
2318            copy=copy,
2319            **opts,
2320        )
2321
2322    def select(
2323        self,
2324        *expressions: ExpOrStr,
2325        append: bool = True,
2326        dialect: DialectType = None,
2327        copy: bool = True,
2328        **opts,
2329    ) -> Select:
2330        """
2331        Append to or set the SELECT expressions.
2332
2333        Example:
2334            >>> Select().select("x", "y").sql()
2335            'SELECT x, y'
2336
2337        Args:
2338            *expressions: the SQL code strings to parse.
2339                If an `Expression` instance is passed, it will be used as-is.
2340            append: if `True`, add to any existing expressions.
2341                Otherwise, this resets the expressions.
2342            dialect: the dialect used to parse the input expressions.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            Select: the modified expression.
2348        """
2349        return _apply_list_builder(
2350            *expressions,
2351            instance=self,
2352            arg="expressions",
2353            append=append,
2354            dialect=dialect,
2355            copy=copy,
2356            **opts,
2357        )
2358
2359    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2360        """
2361        Append to or set the LATERAL expressions.
2362
2363        Example:
2364            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2365            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2366
2367        Args:
2368            *expressions (str | Expression): the SQL code strings to parse.
2369                If an `Expression` instance is passed, it will be used as-is.
2370            append (bool): if `True`, add to any existing expressions.
2371                Otherwise, this resets the expressions.
2372            dialect (str): the dialect used to parse the input expressions.
2373            copy (bool): if `False`, modify this expression instance in-place.
2374            opts (kwargs): other options to use to parse the input expressions.
2375
2376        Returns:
2377            Select: the modified expression.
2378        """
2379        return _apply_list_builder(
2380            *expressions,
2381            instance=self,
2382            arg="laterals",
2383            append=append,
2384            into=Lateral,
2385            prefix="LATERAL VIEW",
2386            dialect=dialect,
2387            copy=copy,
2388            **opts,
2389        )
2390
2391    def join(
2392        self,
2393        expression,
2394        on=None,
2395        using=None,
2396        append=True,
2397        join_type=None,
2398        join_alias=None,
2399        dialect=None,
2400        copy=True,
2401        **opts,
2402    ) -> Select:
2403        """
2404        Append to or set the JOIN expressions.
2405
2406        Example:
2407            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2408            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2409
2410            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2411            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2412
2413            Use `join_type` to change the type of join:
2414
2415            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2416            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2417
2418        Args:
2419            expression (str | Expression): the SQL code string to parse.
2420                If an `Expression` instance is passed, it will be used as-is.
2421            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2422                If an `Expression` instance is passed, it will be used as-is.
2423            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2424                If an `Expression` instance is passed, it will be used as-is.
2425            append (bool): if `True`, add to any existing expressions.
2426                Otherwise, this resets the expressions.
2427            join_type (str): If set, alter the parsed join type
2428            dialect (str): the dialect used to parse the input expressions.
2429            copy (bool): if `False`, modify this expression instance in-place.
2430            opts (kwargs): other options to use to parse the input expressions.
2431
2432        Returns:
2433            Select: the modified expression.
2434        """
2435        parse_args = {"dialect": dialect, **opts}
2436
2437        try:
2438            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2439        except ParseError:
2440            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2441
2442        join = expression if isinstance(expression, Join) else Join(this=expression)
2443
2444        if isinstance(join.this, Select):
2445            join.this.replace(join.this.subquery())
2446
2447        if join_type:
2448            natural: t.Optional[Token]
2449            side: t.Optional[Token]
2450            kind: t.Optional[Token]
2451
2452            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2453
2454            if natural:
2455                join.set("natural", True)
2456            if side:
2457                join.set("side", side.text)
2458            if kind:
2459                join.set("kind", kind.text)
2460
2461        if on:
2462            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2463            join.set("on", on)
2464
2465        if using:
2466            join = _apply_list_builder(
2467                *ensure_collection(using),
2468                instance=join,
2469                arg="using",
2470                append=append,
2471                copy=copy,
2472                **opts,
2473            )
2474
2475        if join_alias:
2476            join.set("this", alias_(join.this, join_alias, table=True))
2477        return _apply_list_builder(
2478            join,
2479            instance=self,
2480            arg="joins",
2481            append=append,
2482            copy=copy,
2483            **opts,
2484        )
2485
2486    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2487        """
2488        Append to or set the WHERE expressions.
2489
2490        Example:
2491            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2492            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2493
2494        Args:
2495            *expressions (str | Expression): the SQL code strings to parse.
2496                If an `Expression` instance is passed, it will be used as-is.
2497                Multiple expressions are combined with an AND operator.
2498            append (bool): if `True`, AND the new expressions to any existing expression.
2499                Otherwise, this resets the expression.
2500            dialect (str): the dialect used to parse the input expressions.
2501            copy (bool): if `False`, modify this expression instance in-place.
2502            opts (kwargs): other options to use to parse the input expressions.
2503
2504        Returns:
2505            Select: the modified expression.
2506        """
2507        return _apply_conjunction_builder(
2508            *expressions,
2509            instance=self,
2510            arg="where",
2511            append=append,
2512            into=Where,
2513            dialect=dialect,
2514            copy=copy,
2515            **opts,
2516        )
2517
2518    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2519        """
2520        Append to or set the HAVING expressions.
2521
2522        Example:
2523            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2524            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2525
2526        Args:
2527            *expressions (str | Expression): the SQL code strings to parse.
2528                If an `Expression` instance is passed, it will be used as-is.
2529                Multiple expressions are combined with an AND operator.
2530            append (bool): if `True`, AND the new expressions to any existing expression.
2531                Otherwise, this resets the expression.
2532            dialect (str): the dialect used to parse the input expressions.
2533            copy (bool): if `False`, modify this expression instance in-place.
2534            opts (kwargs): other options to use to parse the input expressions.
2535
2536        Returns:
2537            Select: the modified expression.
2538        """
2539        return _apply_conjunction_builder(
2540            *expressions,
2541            instance=self,
2542            arg="having",
2543            append=append,
2544            into=Having,
2545            dialect=dialect,
2546            copy=copy,
2547            **opts,
2548        )
2549
2550    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2551        return _apply_list_builder(
2552            *expressions,
2553            instance=self,
2554            arg="windows",
2555            append=append,
2556            into=Window,
2557            dialect=dialect,
2558            copy=copy,
2559            **opts,
2560        )
2561
2562    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2563        return _apply_conjunction_builder(
2564            *expressions,
2565            instance=self,
2566            arg="qualify",
2567            append=append,
2568            into=Qualify,
2569            dialect=dialect,
2570            copy=copy,
2571            **opts,
2572        )
2573
2574    def distinct(self, distinct=True, copy=True) -> Select:
2575        """
2576        Set the OFFSET expression.
2577
2578        Example:
2579            >>> Select().from_("tbl").select("x").distinct().sql()
2580            'SELECT DISTINCT x FROM tbl'
2581
2582        Args:
2583            distinct (bool): whether the Select should be distinct
2584            copy (bool): if `False`, modify this expression instance in-place.
2585
2586        Returns:
2587            Select: the modified expression.
2588        """
2589        instance = _maybe_copy(self, copy)
2590        instance.set("distinct", Distinct() if distinct else None)
2591        return instance
2592
2593    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2594        """
2595        Convert this expression to a CREATE TABLE AS statement.
2596
2597        Example:
2598            >>> Select().select("*").from_("tbl").ctas("x").sql()
2599            'CREATE TABLE x AS SELECT * FROM tbl'
2600
2601        Args:
2602            table (str | Expression): the SQL code string to parse as the table name.
2603                If another `Expression` instance is passed, it will be used as-is.
2604            properties (dict): an optional mapping of table properties
2605            dialect (str): the dialect used to parse the input table.
2606            copy (bool): if `False`, modify this expression instance in-place.
2607            opts (kwargs): other options to use to parse the input table.
2608
2609        Returns:
2610            Create: the CREATE TABLE AS expression
2611        """
2612        instance = _maybe_copy(self, copy)
2613        table_expression = maybe_parse(
2614            table,
2615            into=Table,
2616            dialect=dialect,
2617            **opts,
2618        )
2619        properties_expression = None
2620        if properties:
2621            properties_expression = Properties.from_dict(properties)
2622
2623        return Create(
2624            this=table_expression,
2625            kind="table",
2626            expression=instance,
2627            properties=properties_expression,
2628        )
2629
2630    def lock(self, update: bool = True, copy: bool = True) -> Select:
2631        """
2632        Set the locking read mode for this expression.
2633
2634        Examples:
2635            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2636            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2637
2638            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2639            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2640
2641        Args:
2642            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2643            copy: if `False`, modify this expression instance in-place.
2644
2645        Returns:
2646            The modified expression.
2647        """
2648
2649        inst = _maybe_copy(self, copy)
2650        inst.set("lock", Lock(update=update))
2651
2652        return inst
2653
2654    @property
2655    def named_selects(self) -> t.List[str]:
2656        return [e.output_name for e in self.expressions if e.alias_or_name]
2657
2658    @property
2659    def is_star(self) -> bool:
2660        return any(expression.is_star for expression in self.expressions)
2661
2662    @property
2663    def selects(self) -> t.List[Expression]:
2664        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2092    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2093        """
2094        Set the FROM expression.
2095
2096        Example:
2097            >>> Select().from_("tbl").select("x").sql()
2098            'SELECT x FROM tbl'
2099
2100        Args:
2101            *expressions (str | Expression): the SQL code strings to parse.
2102                If a `From` instance is passed, this is used as-is.
2103                If another `Expression` instance is passed, it will be wrapped in a `From`.
2104            append (bool): if `True`, add to any existing expressions.
2105                Otherwise, this flattens all the `From` expression into a single expression.
2106            dialect (str): the dialect used to parse the input expression.
2107            copy (bool): if `False`, modify this expression instance in-place.
2108            opts (kwargs): other options to use to parse the input expressions.
2109
2110        Returns:
2111            Select: the modified expression.
2112        """
2113        return _apply_child_list_builder(
2114            *expressions,
2115            instance=self,
2116            arg="from",
2117            append=append,
2118            copy=copy,
2119            prefix="FROM",
2120            into=From,
2121            dialect=dialect,
2122            **opts,
2123        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2125    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2126        """
2127        Set the GROUP BY expression.
2128
2129        Example:
2130            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2131            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2132
2133        Args:
2134            *expressions (str | Expression): the SQL code strings to parse.
2135                If a `Group` instance is passed, this is used as-is.
2136                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2137                If nothing is passed in then a group by is not applied to the expression
2138            append (bool): if `True`, add to any existing expressions.
2139                Otherwise, this flattens all the `Group` expression into a single expression.
2140            dialect (str): the dialect used to parse the input expression.
2141            copy (bool): if `False`, modify this expression instance in-place.
2142            opts (kwargs): other options to use to parse the input expressions.
2143
2144        Returns:
2145            Select: the modified expression.
2146        """
2147        if not expressions:
2148            return self if not copy else self.copy()
2149        return _apply_child_list_builder(
2150            *expressions,
2151            instance=self,
2152            arg="group",
2153            append=append,
2154            copy=copy,
2155            prefix="GROUP BY",
2156            into=Group,
2157            dialect=dialect,
2158            **opts,
2159        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2161    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2162        """
2163        Set the ORDER BY expression.
2164
2165        Example:
2166            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2167            'SELECT x FROM tbl ORDER BY x DESC'
2168
2169        Args:
2170            *expressions (str | Expression): the SQL code strings to parse.
2171                If a `Group` instance is passed, this is used as-is.
2172                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2173            append (bool): if `True`, add to any existing expressions.
2174                Otherwise, this flattens all the `Order` expression into a single expression.
2175            dialect (str): the dialect used to parse the input expression.
2176            copy (bool): if `False`, modify this expression instance in-place.
2177            opts (kwargs): other options to use to parse the input expressions.
2178
2179        Returns:
2180            Select: the modified expression.
2181        """
2182        return _apply_child_list_builder(
2183            *expressions,
2184            instance=self,
2185            arg="order",
2186            append=append,
2187            copy=copy,
2188            prefix="ORDER BY",
2189            into=Order,
2190            dialect=dialect,
2191            **opts,
2192        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2194    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2195        """
2196        Set the SORT BY expression.
2197
2198        Example:
2199            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2200            'SELECT x FROM tbl SORT BY x DESC'
2201
2202        Args:
2203            *expressions (str | Expression): the SQL code strings to parse.
2204                If a `Group` instance is passed, this is used as-is.
2205                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2206            append (bool): if `True`, add to any existing expressions.
2207                Otherwise, this flattens all the `Order` expression into a single expression.
2208            dialect (str): the dialect used to parse the input expression.
2209            copy (bool): if `False`, modify this expression instance in-place.
2210            opts (kwargs): other options to use to parse the input expressions.
2211
2212        Returns:
2213            Select: the modified expression.
2214        """
2215        return _apply_child_list_builder(
2216            *expressions,
2217            instance=self,
2218            arg="sort",
2219            append=append,
2220            copy=copy,
2221            prefix="SORT BY",
2222            into=Sort,
2223            dialect=dialect,
2224            **opts,
2225        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2227    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2228        """
2229        Set the CLUSTER BY expression.
2230
2231        Example:
2232            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2233            'SELECT x FROM tbl CLUSTER BY x DESC'
2234
2235        Args:
2236            *expressions (str | Expression): the SQL code strings to parse.
2237                If a `Group` instance is passed, this is used as-is.
2238                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2239            append (bool): if `True`, add to any existing expressions.
2240                Otherwise, this flattens all the `Order` expression into a single expression.
2241            dialect (str): the dialect used to parse the input expression.
2242            copy (bool): if `False`, modify this expression instance in-place.
2243            opts (kwargs): other options to use to parse the input expressions.
2244
2245        Returns:
2246            Select: the modified expression.
2247        """
2248        return _apply_child_list_builder(
2249            *expressions,
2250            instance=self,
2251            arg="cluster",
2252            append=append,
2253            copy=copy,
2254            prefix="CLUSTER BY",
2255            into=Cluster,
2256            dialect=dialect,
2257            **opts,
2258        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2260    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2261        """
2262        Set the LIMIT expression.
2263
2264        Example:
2265            >>> Select().from_("tbl").select("x").limit(10).sql()
2266            'SELECT x FROM tbl LIMIT 10'
2267
2268        Args:
2269            expression (str | int | Expression): the SQL code string to parse.
2270                This can also be an integer.
2271                If a `Limit` instance is passed, this is used as-is.
2272                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2273            dialect (str): the dialect used to parse the input expression.
2274            copy (bool): if `False`, modify this expression instance in-place.
2275            opts (kwargs): other options to use to parse the input expressions.
2276
2277        Returns:
2278            Select: the modified expression.
2279        """
2280        return _apply_builder(
2281            expression=expression,
2282            instance=self,
2283            arg="limit",
2284            into=Limit,
2285            prefix="LIMIT",
2286            dialect=dialect,
2287            copy=copy,
2288            **opts,
2289        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2291    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2292        """
2293        Set the OFFSET expression.
2294
2295        Example:
2296            >>> Select().from_("tbl").select("x").offset(10).sql()
2297            'SELECT x FROM tbl OFFSET 10'
2298
2299        Args:
2300            expression (str | int | Expression): the SQL code string to parse.
2301                This can also be an integer.
2302                If a `Offset` instance is passed, this is used as-is.
2303                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2304            dialect (str): the dialect used to parse the input expression.
2305            copy (bool): if `False`, modify this expression instance in-place.
2306            opts (kwargs): other options to use to parse the input expressions.
2307
2308        Returns:
2309            Select: the modified expression.
2310        """
2311        return _apply_builder(
2312            expression=expression,
2313            instance=self,
2314            arg="offset",
2315            into=Offset,
2316            prefix="OFFSET",
2317            dialect=dialect,
2318            copy=copy,
2319            **opts,
2320        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2322    def select(
2323        self,
2324        *expressions: ExpOrStr,
2325        append: bool = True,
2326        dialect: DialectType = None,
2327        copy: bool = True,
2328        **opts,
2329    ) -> Select:
2330        """
2331        Append to or set the SELECT expressions.
2332
2333        Example:
2334            >>> Select().select("x", "y").sql()
2335            'SELECT x, y'
2336
2337        Args:
2338            *expressions: the SQL code strings to parse.
2339                If an `Expression` instance is passed, it will be used as-is.
2340            append: if `True`, add to any existing expressions.
2341                Otherwise, this resets the expressions.
2342            dialect: the dialect used to parse the input expressions.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            Select: the modified expression.
2348        """
2349        return _apply_list_builder(
2350            *expressions,
2351            instance=self,
2352            arg="expressions",
2353            append=append,
2354            dialect=dialect,
2355            copy=copy,
2356            **opts,
2357        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2359    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2360        """
2361        Append to or set the LATERAL expressions.
2362
2363        Example:
2364            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2365            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2366
2367        Args:
2368            *expressions (str | Expression): the SQL code strings to parse.
2369                If an `Expression` instance is passed, it will be used as-is.
2370            append (bool): if `True`, add to any existing expressions.
2371                Otherwise, this resets the expressions.
2372            dialect (str): the dialect used to parse the input expressions.
2373            copy (bool): if `False`, modify this expression instance in-place.
2374            opts (kwargs): other options to use to parse the input expressions.
2375
2376        Returns:
2377            Select: the modified expression.
2378        """
2379        return _apply_list_builder(
2380            *expressions,
2381            instance=self,
2382            arg="laterals",
2383            append=append,
2384            into=Lateral,
2385            prefix="LATERAL VIEW",
2386            dialect=dialect,
2387            copy=copy,
2388            **opts,
2389        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2391    def join(
2392        self,
2393        expression,
2394        on=None,
2395        using=None,
2396        append=True,
2397        join_type=None,
2398        join_alias=None,
2399        dialect=None,
2400        copy=True,
2401        **opts,
2402    ) -> Select:
2403        """
2404        Append to or set the JOIN expressions.
2405
2406        Example:
2407            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2408            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2409
2410            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2411            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2412
2413            Use `join_type` to change the type of join:
2414
2415            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2416            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2417
2418        Args:
2419            expression (str | Expression): the SQL code string to parse.
2420                If an `Expression` instance is passed, it will be used as-is.
2421            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2422                If an `Expression` instance is passed, it will be used as-is.
2423            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2424                If an `Expression` instance is passed, it will be used as-is.
2425            append (bool): if `True`, add to any existing expressions.
2426                Otherwise, this resets the expressions.
2427            join_type (str): If set, alter the parsed join type
2428            dialect (str): the dialect used to parse the input expressions.
2429            copy (bool): if `False`, modify this expression instance in-place.
2430            opts (kwargs): other options to use to parse the input expressions.
2431
2432        Returns:
2433            Select: the modified expression.
2434        """
2435        parse_args = {"dialect": dialect, **opts}
2436
2437        try:
2438            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2439        except ParseError:
2440            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2441
2442        join = expression if isinstance(expression, Join) else Join(this=expression)
2443
2444        if isinstance(join.this, Select):
2445            join.this.replace(join.this.subquery())
2446
2447        if join_type:
2448            natural: t.Optional[Token]
2449            side: t.Optional[Token]
2450            kind: t.Optional[Token]
2451
2452            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2453
2454            if natural:
2455                join.set("natural", True)
2456            if side:
2457                join.set("side", side.text)
2458            if kind:
2459                join.set("kind", kind.text)
2460
2461        if on:
2462            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2463            join.set("on", on)
2464
2465        if using:
2466            join = _apply_list_builder(
2467                *ensure_collection(using),
2468                instance=join,
2469                arg="using",
2470                append=append,
2471                copy=copy,
2472                **opts,
2473            )
2474
2475        if join_alias:
2476            join.set("this", alias_(join.this, join_alias, table=True))
2477        return _apply_list_builder(
2478            join,
2479            instance=self,
2480            arg="joins",
2481            append=append,
2482            copy=copy,
2483            **opts,
2484        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2486    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2487        """
2488        Append to or set the WHERE expressions.
2489
2490        Example:
2491            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2492            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2493
2494        Args:
2495            *expressions (str | Expression): the SQL code strings to parse.
2496                If an `Expression` instance is passed, it will be used as-is.
2497                Multiple expressions are combined with an AND operator.
2498            append (bool): if `True`, AND the new expressions to any existing expression.
2499                Otherwise, this resets the expression.
2500            dialect (str): the dialect used to parse the input expressions.
2501            copy (bool): if `False`, modify this expression instance in-place.
2502            opts (kwargs): other options to use to parse the input expressions.
2503
2504        Returns:
2505            Select: the modified expression.
2506        """
2507        return _apply_conjunction_builder(
2508            *expressions,
2509            instance=self,
2510            arg="where",
2511            append=append,
2512            into=Where,
2513            dialect=dialect,
2514            copy=copy,
2515            **opts,
2516        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2518    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2519        """
2520        Append to or set the HAVING expressions.
2521
2522        Example:
2523            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2524            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2525
2526        Args:
2527            *expressions (str | Expression): the SQL code strings to parse.
2528                If an `Expression` instance is passed, it will be used as-is.
2529                Multiple expressions are combined with an AND operator.
2530            append (bool): if `True`, AND the new expressions to any existing expression.
2531                Otherwise, this resets the expression.
2532            dialect (str): the dialect used to parse the input expressions.
2533            copy (bool): if `False`, modify this expression instance in-place.
2534            opts (kwargs): other options to use to parse the input expressions.
2535
2536        Returns:
2537            Select: the modified expression.
2538        """
2539        return _apply_conjunction_builder(
2540            *expressions,
2541            instance=self,
2542            arg="having",
2543            append=append,
2544            into=Having,
2545            dialect=dialect,
2546            copy=copy,
2547            **opts,
2548        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2550    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2551        return _apply_list_builder(
2552            *expressions,
2553            instance=self,
2554            arg="windows",
2555            append=append,
2556            into=Window,
2557            dialect=dialect,
2558            copy=copy,
2559            **opts,
2560        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2562    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2563        return _apply_conjunction_builder(
2564            *expressions,
2565            instance=self,
2566            arg="qualify",
2567            append=append,
2568            into=Qualify,
2569            dialect=dialect,
2570            copy=copy,
2571            **opts,
2572        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2574    def distinct(self, distinct=True, copy=True) -> Select:
2575        """
2576        Set the OFFSET expression.
2577
2578        Example:
2579            >>> Select().from_("tbl").select("x").distinct().sql()
2580            'SELECT DISTINCT x FROM tbl'
2581
2582        Args:
2583            distinct (bool): whether the Select should be distinct
2584            copy (bool): if `False`, modify this expression instance in-place.
2585
2586        Returns:
2587            Select: the modified expression.
2588        """
2589        instance = _maybe_copy(self, copy)
2590        instance.set("distinct", Distinct() if distinct else None)
2591        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2593    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2594        """
2595        Convert this expression to a CREATE TABLE AS statement.
2596
2597        Example:
2598            >>> Select().select("*").from_("tbl").ctas("x").sql()
2599            'CREATE TABLE x AS SELECT * FROM tbl'
2600
2601        Args:
2602            table (str | Expression): the SQL code string to parse as the table name.
2603                If another `Expression` instance is passed, it will be used as-is.
2604            properties (dict): an optional mapping of table properties
2605            dialect (str): the dialect used to parse the input table.
2606            copy (bool): if `False`, modify this expression instance in-place.
2607            opts (kwargs): other options to use to parse the input table.
2608
2609        Returns:
2610            Create: the CREATE TABLE AS expression
2611        """
2612        instance = _maybe_copy(self, copy)
2613        table_expression = maybe_parse(
2614            table,
2615            into=Table,
2616            dialect=dialect,
2617            **opts,
2618        )
2619        properties_expression = None
2620        if properties:
2621            properties_expression = Properties.from_dict(properties)
2622
2623        return Create(
2624            this=table_expression,
2625            kind="table",
2626            expression=instance,
2627            properties=properties_expression,
2628        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2630    def lock(self, update: bool = True, copy: bool = True) -> Select:
2631        """
2632        Set the locking read mode for this expression.
2633
2634        Examples:
2635            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2636            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2637
2638            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2639            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2640
2641        Args:
2642            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2643            copy: if `False`, modify this expression instance in-place.
2644
2645        Returns:
2646            The modified expression.
2647        """
2648
2649        inst = _maybe_copy(self, copy)
2650        inst.set("lock", Lock(update=update))
2651
2652        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2667class Subquery(DerivedTable, Unionable):
2668    arg_types = {
2669        "this": True,
2670        "alias": False,
2671        "with": False,
2672        **QUERY_MODIFIERS,
2673    }
2674
2675    def unnest(self):
2676        """
2677        Returns the first non subquery.
2678        """
2679        expression = self
2680        while isinstance(expression, Subquery):
2681            expression = expression.this
2682        return expression
2683
2684    @property
2685    def is_star(self) -> bool:
2686        return self.this.is_star
2687
2688    @property
2689    def output_name(self):
2690        return self.alias
def unnest(self):
2675    def unnest(self):
2676        """
2677        Returns the first non subquery.
2678        """
2679        expression = self
2680        while isinstance(expression, Subquery):
2681            expression = expression.this
2682        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2693class TableSample(Expression):
2694    arg_types = {
2695        "this": False,
2696        "method": False,
2697        "bucket_numerator": False,
2698        "bucket_denominator": False,
2699        "bucket_field": False,
2700        "percent": False,
2701        "rows": False,
2702        "size": False,
2703        "seed": False,
2704        "kind": False,
2705    }
class Tag(Expression):
2708class Tag(Expression):
2709    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2710
2711    arg_types = {
2712        "this": False,
2713        "prefix": False,
2714        "postfix": False,
2715    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2718class Pivot(Expression):
2719    arg_types = {
2720        "this": False,
2721        "alias": False,
2722        "expressions": True,
2723        "field": True,
2724        "unpivot": True,
2725    }
class Window(Expression):
2728class Window(Expression):
2729    arg_types = {
2730        "this": True,
2731        "partition_by": False,
2732        "order": False,
2733        "spec": False,
2734        "alias": False,
2735    }
class WindowSpec(Expression):
2738class WindowSpec(Expression):
2739    arg_types = {
2740        "kind": False,
2741        "start": False,
2742        "start_side": False,
2743        "end": False,
2744        "end_side": False,
2745    }
class Where(Expression):
2748class Where(Expression):
2749    pass
class Star(Expression):
2752class Star(Expression):
2753    arg_types = {"except": False, "replace": False}
2754
2755    @property
2756    def name(self) -> str:
2757        return "*"
2758
2759    @property
2760    def output_name(self):
2761        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2764class Parameter(Expression):
2765    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2768class SessionParameter(Expression):
2769    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2772class Placeholder(Expression):
2773    arg_types = {"this": False}
class Null(Condition):
2776class Null(Condition):
2777    arg_types: t.Dict[str, t.Any] = {}
2778
2779    @property
2780    def name(self) -> str:
2781        return "NULL"
class Boolean(Condition):
2784class Boolean(Condition):
2785    pass
class DataType(Expression):
2788class DataType(Expression):
2789    arg_types = {
2790        "this": True,
2791        "expressions": False,
2792        "nested": False,
2793        "values": False,
2794        "prefix": False,
2795    }
2796
2797    class Type(AutoName):
2798        CHAR = auto()
2799        NCHAR = auto()
2800        VARCHAR = auto()
2801        NVARCHAR = auto()
2802        TEXT = auto()
2803        MEDIUMTEXT = auto()
2804        LONGTEXT = auto()
2805        MEDIUMBLOB = auto()
2806        LONGBLOB = auto()
2807        BINARY = auto()
2808        VARBINARY = auto()
2809        INT = auto()
2810        UINT = auto()
2811        TINYINT = auto()
2812        UTINYINT = auto()
2813        SMALLINT = auto()
2814        USMALLINT = auto()
2815        BIGINT = auto()
2816        UBIGINT = auto()
2817        FLOAT = auto()
2818        DOUBLE = auto()
2819        DECIMAL = auto()
2820        BIT = auto()
2821        BOOLEAN = auto()
2822        JSON = auto()
2823        JSONB = auto()
2824        INTERVAL = auto()
2825        TIME = auto()
2826        TIMESTAMP = auto()
2827        TIMESTAMPTZ = auto()
2828        TIMESTAMPLTZ = auto()
2829        DATE = auto()
2830        DATETIME = auto()
2831        ARRAY = auto()
2832        MAP = auto()
2833        UUID = auto()
2834        GEOGRAPHY = auto()
2835        GEOMETRY = auto()
2836        STRUCT = auto()
2837        NULLABLE = auto()
2838        HLLSKETCH = auto()
2839        HSTORE = auto()
2840        SUPER = auto()
2841        SERIAL = auto()
2842        SMALLSERIAL = auto()
2843        BIGSERIAL = auto()
2844        XML = auto()
2845        UNIQUEIDENTIFIER = auto()
2846        MONEY = auto()
2847        SMALLMONEY = auto()
2848        ROWVERSION = auto()
2849        IMAGE = auto()
2850        VARIANT = auto()
2851        OBJECT = auto()
2852        INET = auto()
2853        NULL = auto()
2854        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2855
2856    TEXT_TYPES = {
2857        Type.CHAR,
2858        Type.NCHAR,
2859        Type.VARCHAR,
2860        Type.NVARCHAR,
2861        Type.TEXT,
2862    }
2863
2864    INTEGER_TYPES = {
2865        Type.INT,
2866        Type.TINYINT,
2867        Type.SMALLINT,
2868        Type.BIGINT,
2869    }
2870
2871    FLOAT_TYPES = {
2872        Type.FLOAT,
2873        Type.DOUBLE,
2874    }
2875
2876    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2877
2878    TEMPORAL_TYPES = {
2879        Type.TIMESTAMP,
2880        Type.TIMESTAMPTZ,
2881        Type.TIMESTAMPLTZ,
2882        Type.DATE,
2883        Type.DATETIME,
2884    }
2885
2886    @classmethod
2887    def build(
2888        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2889    ) -> DataType:
2890        from sqlglot import parse_one
2891
2892        if isinstance(dtype, str):
2893            if dtype.upper() in cls.Type.__members__:
2894                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2895            else:
2896                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2897            if data_type_exp is None:
2898                raise ValueError(f"Unparsable data type value: {dtype}")
2899        elif isinstance(dtype, DataType.Type):
2900            data_type_exp = DataType(this=dtype)
2901        elif isinstance(dtype, DataType):
2902            return dtype
2903        else:
2904            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2905        return DataType(**{**data_type_exp.args, **kwargs})
2906
2907    def is_type(self, dtype: DataType.Type) -> bool:
2908        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2886    @classmethod
2887    def build(
2888        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2889    ) -> DataType:
2890        from sqlglot import parse_one
2891
2892        if isinstance(dtype, str):
2893            if dtype.upper() in cls.Type.__members__:
2894                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2895            else:
2896                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2897            if data_type_exp is None:
2898                raise ValueError(f"Unparsable data type value: {dtype}")
2899        elif isinstance(dtype, DataType.Type):
2900            data_type_exp = DataType(this=dtype)
2901        elif isinstance(dtype, DataType):
2902            return dtype
2903        else:
2904            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2905        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2907    def is_type(self, dtype: DataType.Type) -> bool:
2908        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2797    class Type(AutoName):
2798        CHAR = auto()
2799        NCHAR = auto()
2800        VARCHAR = auto()
2801        NVARCHAR = auto()
2802        TEXT = auto()
2803        MEDIUMTEXT = auto()
2804        LONGTEXT = auto()
2805        MEDIUMBLOB = auto()
2806        LONGBLOB = auto()
2807        BINARY = auto()
2808        VARBINARY = auto()
2809        INT = auto()
2810        UINT = auto()
2811        TINYINT = auto()
2812        UTINYINT = auto()
2813        SMALLINT = auto()
2814        USMALLINT = auto()
2815        BIGINT = auto()
2816        UBIGINT = auto()
2817        FLOAT = auto()
2818        DOUBLE = auto()
2819        DECIMAL = auto()
2820        BIT = auto()
2821        BOOLEAN = auto()
2822        JSON = auto()
2823        JSONB = auto()
2824        INTERVAL = auto()
2825        TIME = auto()
2826        TIMESTAMP = auto()
2827        TIMESTAMPTZ = auto()
2828        TIMESTAMPLTZ = auto()
2829        DATE = auto()
2830        DATETIME = auto()
2831        ARRAY = auto()
2832        MAP = auto()
2833        UUID = auto()
2834        GEOGRAPHY = auto()
2835        GEOMETRY = auto()
2836        STRUCT = auto()
2837        NULLABLE = auto()
2838        HLLSKETCH = auto()
2839        HSTORE = auto()
2840        SUPER = auto()
2841        SERIAL = auto()
2842        SMALLSERIAL = auto()
2843        BIGSERIAL = auto()
2844        XML = auto()
2845        UNIQUEIDENTIFIER = auto()
2846        MONEY = auto()
2847        SMALLMONEY = auto()
2848        ROWVERSION = auto()
2849        IMAGE = auto()
2850        VARIANT = auto()
2851        OBJECT = auto()
2852        INET = auto()
2853        NULL = auto()
2854        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2912class PseudoType(Expression):
2913    pass
class StructKwarg(Expression):
2916class StructKwarg(Expression):
2917    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2921class SubqueryPredicate(Predicate):
2922    pass
class All(SubqueryPredicate):
2925class All(SubqueryPredicate):
2926    pass
class Any(SubqueryPredicate):
2929class Any(SubqueryPredicate):
2930    pass
class Exists(SubqueryPredicate):
2933class Exists(SubqueryPredicate):
2934    pass
class Command(Expression):
2939class Command(Expression):
2940    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2943class Transaction(Expression):
2944    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2947class Commit(Expression):
2948    arg_types = {"chain": False}
class Rollback(Expression):
2951class Rollback(Expression):
2952    arg_types = {"savepoint": False}
class AlterTable(Expression):
2955class AlterTable(Expression):
2956    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2959class AddConstraint(Expression):
2960    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2963class DropPartition(Expression):
2964    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2968class Binary(Expression):
2969    arg_types = {"this": True, "expression": True}
2970
2971    @property
2972    def left(self):
2973        return self.this
2974
2975    @property
2976    def right(self):
2977        return self.expression
class Add(Binary):
2980class Add(Binary):
2981    pass
class Connector(Binary, Condition):
2984class Connector(Binary, Condition):
2985    pass
class And(Connector):
2988class And(Connector):
2989    pass
class Or(Connector):
2992class Or(Connector):
2993    pass
class BitwiseAnd(Binary):
2996class BitwiseAnd(Binary):
2997    pass
class BitwiseLeftShift(Binary):
3000class BitwiseLeftShift(Binary):
3001    pass
class BitwiseOr(Binary):
3004class BitwiseOr(Binary):
3005    pass
class BitwiseRightShift(Binary):
3008class BitwiseRightShift(Binary):
3009    pass
class BitwiseXor(Binary):
3012class BitwiseXor(Binary):
3013    pass
class Div(Binary):
3016class Div(Binary):
3017    pass
class Overlaps(Binary):
3020class Overlaps(Binary):
3021    pass
class Dot(Binary):
3024class Dot(Binary):
3025    @property
3026    def name(self) -> str:
3027        return self.expression.name
3028
3029    @classmethod
3030    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3031        """Build a Dot object with a sequence of expressions."""
3032        if len(expressions) < 2:
3033            raise ValueError(f"Dot requires >= 2 expressions.")
3034
3035        a, b, *expressions = expressions
3036        dot = Dot(this=a, expression=b)
3037
3038        for expression in expressions:
3039            dot = Dot(this=dot, expression=expression)
3040
3041        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3029    @classmethod
3030    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3031        """Build a Dot object with a sequence of expressions."""
3032        if len(expressions) < 2:
3033            raise ValueError(f"Dot requires >= 2 expressions.")
3034
3035        a, b, *expressions = expressions
3036        dot = Dot(this=a, expression=b)
3037
3038        for expression in expressions:
3039            dot = Dot(this=dot, expression=expression)
3040
3041        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3044class DPipe(Binary):
3045    pass
class EQ(Binary, Predicate):
3048class EQ(Binary, Predicate):
3049    pass
class NullSafeEQ(Binary, Predicate):
3052class NullSafeEQ(Binary, Predicate):
3053    pass
class NullSafeNEQ(Binary, Predicate):
3056class NullSafeNEQ(Binary, Predicate):
3057    pass
class Distance(Binary):
3060class Distance(Binary):
3061    pass
class Escape(Binary):
3064class Escape(Binary):
3065    pass
class Glob(Binary, Predicate):
3068class Glob(Binary, Predicate):
3069    pass
class GT(Binary, Predicate):
3072class GT(Binary, Predicate):
3073    pass
class GTE(Binary, Predicate):
3076class GTE(Binary, Predicate):
3077    pass
class ILike(Binary, Predicate):
3080class ILike(Binary, Predicate):
3081    pass
class ILikeAny(Binary, Predicate):
3084class ILikeAny(Binary, Predicate):
3085    pass
class IntDiv(Binary):
3088class IntDiv(Binary):
3089    pass
class Is(Binary, Predicate):
3092class Is(Binary, Predicate):
3093    pass
class Kwarg(Binary):
3096class Kwarg(Binary):
3097    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3100class Like(Binary, Predicate):
3101    pass
class LikeAny(Binary, Predicate):
3104class LikeAny(Binary, Predicate):
3105    pass
class LT(Binary, Predicate):
3108class LT(Binary, Predicate):
3109    pass
class LTE(Binary, Predicate):
3112class LTE(Binary, Predicate):
3113    pass
class Mod(Binary):
3116class Mod(Binary):
3117    pass
class Mul(Binary):
3120class Mul(Binary):
3121    pass
class NEQ(Binary, Predicate):
3124class NEQ(Binary, Predicate):
3125    pass
class SimilarTo(Binary, Predicate):
3128class SimilarTo(Binary, Predicate):
3129    pass
class Slice(Binary):
3132class Slice(Binary):
3133    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3136class Sub(Binary):
3137    pass
class ArrayOverlaps(Binary):
3140class ArrayOverlaps(Binary):
3141    pass
class Unary(Expression):
3146class Unary(Expression):
3147    pass
class BitwiseNot(Unary):
3150class BitwiseNot(Unary):
3151    pass
class Not(Unary, Condition):
3154class Not(Unary, Condition):
3155    pass
class Paren(Unary, Condition):
3158class Paren(Unary, Condition):
3159    arg_types = {"this": True, "with": False}
class Neg(Unary):
3162class Neg(Unary):
3163    pass
class Alias(Expression):
3167class Alias(Expression):
3168    arg_types = {"this": True, "alias": False}
3169
3170    @property
3171    def output_name(self):
3172        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3175class Aliases(Expression):
3176    arg_types = {"this": True, "expressions": True}
3177
3178    @property
3179    def aliases(self):
3180        return self.expressions
class AtTimeZone(Expression):
3183class AtTimeZone(Expression):
3184    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3187class Between(Predicate):
3188    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3191class Bracket(Condition):
3192    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3195class Distinct(Expression):
3196    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3199class In(Predicate):
3200    arg_types = {
3201        "this": True,
3202        "expressions": False,
3203        "query": False,
3204        "unnest": False,
3205        "field": False,
3206        "is_global": False,
3207    }
class TimeUnit(Expression):
3210class TimeUnit(Expression):
3211    """Automatically converts unit arg into a var."""
3212
3213    arg_types = {"unit": False}
3214
3215    def __init__(self, **args):
3216        unit = args.get("unit")
3217        if isinstance(unit, (Column, Literal)):
3218            args["unit"] = Var(this=unit.name)
3219        elif isinstance(unit, Week):
3220            unit.set("this", Var(this=unit.this.name))
3221        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3215    def __init__(self, **args):
3216        unit = args.get("unit")
3217        if isinstance(unit, (Column, Literal)):
3218            args["unit"] = Var(this=unit.name)
3219        elif isinstance(unit, Week):
3220            unit.set("this", Var(this=unit.this.name))
3221        super().__init__(**args)
class Interval(TimeUnit):
3224class Interval(TimeUnit):
3225    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3228class IgnoreNulls(Expression):
3229    pass
class RespectNulls(Expression):
3232class RespectNulls(Expression):
3233    pass
class Func(Condition):
3237class Func(Condition):
3238    """
3239    The base class for all function expressions.
3240
3241    Attributes:
3242        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3243            treated as a variable length argument and the argument's value will be stored as a list.
3244        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3245            for this function expression. These values are used to map this node to a name during parsing
3246            as well as to provide the function's name during SQL string generation. By default the SQL
3247            name is set to the expression's class name transformed to snake case.
3248    """
3249
3250    is_var_len_args = False
3251
3252    @classmethod
3253    def from_arg_list(cls, args):
3254        if cls.is_var_len_args:
3255            all_arg_keys = list(cls.arg_types)
3256            # If this function supports variable length argument treat the last argument as such.
3257            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3258            num_non_var = len(non_var_len_arg_keys)
3259
3260            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3261            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3262        else:
3263            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3264
3265        return cls(**args_dict)
3266
3267    @classmethod
3268    def sql_names(cls):
3269        if cls is Func:
3270            raise NotImplementedError(
3271                "SQL name is only supported by concrete function implementations"
3272            )
3273        if "_sql_names" not in cls.__dict__:
3274            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3275        return cls._sql_names
3276
3277    @classmethod
3278    def sql_name(cls):
3279        return cls.sql_names()[0]
3280
3281    @classmethod
3282    def default_parser_mappings(cls):
3283        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3252    @classmethod
3253    def from_arg_list(cls, args):
3254        if cls.is_var_len_args:
3255            all_arg_keys = list(cls.arg_types)
3256            # If this function supports variable length argument treat the last argument as such.
3257            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3258            num_non_var = len(non_var_len_arg_keys)
3259
3260            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3261            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3262        else:
3263            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3264
3265        return cls(**args_dict)
@classmethod
def sql_names(cls):
3267    @classmethod
3268    def sql_names(cls):
3269        if cls is Func:
3270            raise NotImplementedError(
3271                "SQL name is only supported by concrete function implementations"
3272            )
3273        if "_sql_names" not in cls.__dict__:
3274            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3275        return cls._sql_names
@classmethod
def sql_name(cls):
3277    @classmethod
3278    def sql_name(cls):
3279        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3281    @classmethod
3282    def default_parser_mappings(cls):
3283        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3286class AggFunc(Func):
3287    pass
class Abs(Func):
3290class Abs(Func):
3291    pass
class Anonymous(Func):
3294class Anonymous(Func):
3295    arg_types = {"this": True, "expressions": False}
3296    is_var_len_args = True
class Hll(AggFunc):
3301class Hll(AggFunc):
3302    arg_types = {"this": True, "expressions": False}
3303    is_var_len_args = True
class ApproxDistinct(AggFunc):
3306class ApproxDistinct(AggFunc):
3307    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3310class Array(Func):
3311    arg_types = {"expressions": False}
3312    is_var_len_args = True
class ToChar(Func):
3316class ToChar(Func):
3317    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3320class GenerateSeries(Func):
3321    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3324class ArrayAgg(AggFunc):
3325    pass
class ArrayAll(Func):
3328class ArrayAll(Func):
3329    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3332class ArrayAny(Func):
3333    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3336class ArrayConcat(Func):
3337    arg_types = {"this": True, "expressions": False}
3338    is_var_len_args = True
class ArrayContains(Binary, Func):
3341class ArrayContains(Binary, Func):
3342    pass
class ArrayContained(Binary):
3345class ArrayContained(Binary):
3346    pass
class ArrayFilter(Func):
3349class ArrayFilter(Func):
3350    arg_types = {"this": True, "expression": True}
3351    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3354class ArrayJoin(Func):
3355    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3358class ArraySize(Func):
3359    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3362class ArraySort(Func):
3363    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3366class ArraySum(Func):
3367    pass
class ArrayUnionAgg(AggFunc):
3370class ArrayUnionAgg(AggFunc):
3371    pass
class Avg(AggFunc):
3374class Avg(AggFunc):
3375    pass
class AnyValue(AggFunc):
3378class AnyValue(AggFunc):
3379    pass
class Case(Func):
3382class Case(Func):
3383    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3386class Cast(Func):
3387    arg_types = {"this": True, "to": True}
3388
3389    @property
3390    def name(self) -> str:
3391        return self.this.name
3392
3393    @property
3394    def to(self):
3395        return self.args["to"]
3396
3397    @property
3398    def output_name(self):
3399        return self.name
3400
3401    def is_type(self, dtype: DataType.Type) -> bool:
3402        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3401    def is_type(self, dtype: DataType.Type) -> bool:
3402        return self.to.is_type(dtype)
class Collate(Binary):
3405class Collate(Binary):
3406    pass
class TryCast(Cast):
3409class TryCast(Cast):
3410    pass
class Ceil(Func):
3413class Ceil(Func):
3414    arg_types = {"this": True, "decimals": False}
3415    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3418class Coalesce(Func):
3419    arg_types = {"this": True, "expressions": False}
3420    is_var_len_args = True
class Concat(Func):
3423class Concat(Func):
3424    arg_types = {"expressions": True}
3425    is_var_len_args = True
class ConcatWs(Concat):
3428class ConcatWs(Concat):
3429    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3432class Count(AggFunc):
3433    arg_types = {"this": False}
class CountIf(AggFunc):
3436class CountIf(AggFunc):
3437    pass
class CurrentDate(Func):
3440class CurrentDate(Func):
3441    arg_types = {"this": False}
class CurrentDatetime(Func):
3444class CurrentDatetime(Func):
3445    arg_types = {"this": False}
class CurrentTime(Func):
3448class CurrentTime(Func):
3449    arg_types = {"this": False}
class CurrentTimestamp(Func):
3452class CurrentTimestamp(Func):
3453    arg_types = {"this": False}
class CurrentUser(Func):
3456class CurrentUser(Func):
3457    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3460class DateAdd(Func, TimeUnit):
3461    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3464class DateSub(Func, TimeUnit):
3465    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3468class DateDiff(Func, TimeUnit):
3469    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3470    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3473class DateTrunc(Func):
3474    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3477class DatetimeAdd(Func, TimeUnit):
3478    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3481class DatetimeSub(Func, TimeUnit):
3482    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3485class DatetimeDiff(Func, TimeUnit):
3486    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3489class DatetimeTrunc(Func, TimeUnit):
3490    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3493class DayOfWeek(Func):
3494    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3497class DayOfMonth(Func):
3498    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3501class DayOfYear(Func):
3502    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3505class WeekOfYear(Func):
3506    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3509class LastDateOfMonth(Func):
3510    pass
class Extract(Func):
3513class Extract(Func):
3514    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3517class TimestampAdd(Func, TimeUnit):
3518    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3521class TimestampSub(Func, TimeUnit):
3522    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3525class TimestampDiff(Func, TimeUnit):
3526    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3529class TimestampTrunc(Func, TimeUnit):
3530    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3533class TimeAdd(Func, TimeUnit):
3534    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3537class TimeSub(Func, TimeUnit):
3538    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3541class TimeDiff(Func, TimeUnit):
3542    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3545class TimeTrunc(Func, TimeUnit):
3546    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3549class DateFromParts(Func):
3550    _sql_names = ["DATEFROMPARTS"]
3551    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3554class DateStrToDate(Func):
3555    pass
class DateToDateStr(Func):
3558class DateToDateStr(Func):
3559    pass
class DateToDi(Func):
3562class DateToDi(Func):
3563    pass
class Day(Func):
3566class Day(Func):
3567    pass
class Decode(Func):
3570class Decode(Func):
3571    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3574class DiToDate(Func):
3575    pass
class Encode(Func):
3578class Encode(Func):
3579    arg_types = {"this": True, "charset": True}
class Exp(Func):
3582class Exp(Func):
3583    pass
class Explode(Func):
3586class Explode(Func):
3587    pass
class ExponentialTimeDecayedAvg(AggFunc):
3590class ExponentialTimeDecayedAvg(AggFunc):
3591    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3594class Floor(Func):
3595    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3598class Greatest(Func):
3599    arg_types = {"this": True, "expressions": False}
3600    is_var_len_args = True
class GroupConcat(Func):
3603class GroupConcat(Func):
3604    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3607class GroupUniqArray(AggFunc):
3608    arg_types = {"this": True, "size": False}
class Hex(Func):
3611class Hex(Func):
3612    pass
class Histogram(AggFunc):
3615class Histogram(AggFunc):
3616    arg_types = {"this": True, "bins": False}
class If(Func):
3619class If(Func):
3620    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3623class IfNull(Func):
3624    arg_types = {"this": True, "expression": False}
3625    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3628class Initcap(Func):
3629    pass
class JSONKeyValue(Expression):
3632class JSONKeyValue(Expression):
3633    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3636class JSONObject(Func):
3637    arg_types = {
3638        "expressions": False,
3639        "null_handling": False,
3640        "unique_keys": False,
3641        "return_type": False,
3642        "format_json": False,
3643        "encoding": False,
3644    }
class JSONBContains(Binary):
3647class JSONBContains(Binary):
3648    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3651class JSONExtract(Binary, Func):
3652    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3655class JSONExtractScalar(JSONExtract):
3656    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3659class JSONBExtract(JSONExtract):
3660    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3663class JSONBExtractScalar(JSONExtract):
3664    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3667class JSONFormat(Func):
3668    arg_types = {"this": False, "options": False}
3669    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3672class Least(Func):
3673    arg_types = {"expressions": False}
3674    is_var_len_args = True
class Length(Func):
3677class Length(Func):
3678    pass
class Levenshtein(Func):
3681class Levenshtein(Func):
3682    arg_types = {
3683        "this": True,
3684        "expression": False,
3685        "ins_cost": False,
3686        "del_cost": False,
3687        "sub_cost": False,
3688    }
class Ln(Func):
3691class Ln(Func):
3692    pass
class Log(Func):
3695class Log(Func):
3696    arg_types = {"this": True, "expression": False}
class Log2(Func):
3699class Log2(Func):
3700    pass
class Log10(Func):
3703class Log10(Func):
3704    pass
class LogicalOr(AggFunc):
3707class LogicalOr(AggFunc):
3708    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3711class LogicalAnd(AggFunc):
3712    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3715class Lower(Func):
3716    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3719class Map(Func):
3720    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3723class VarMap(Func):
3724    arg_types = {"keys": True, "values": True}
3725    is_var_len_args = True
class MatchAgainst(Func):
3729class MatchAgainst(Func):
3730    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3733class Max(AggFunc):
3734    arg_types = {"this": True, "expressions": False}
3735    is_var_len_args = True
class Min(AggFunc):
3738class Min(AggFunc):
3739    arg_types = {"this": True, "expressions": False}
3740    is_var_len_args = True
class Month(Func):
3743class Month(Func):
3744    pass
class Nvl2(Func):
3747class Nvl2(Func):
3748    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3751class Posexplode(Func):
3752    pass
class Pow(Binary, Func):
3755class Pow(Binary, Func):
3756    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3759class PercentileCont(AggFunc):
3760    pass
class PercentileDisc(AggFunc):
3763class PercentileDisc(AggFunc):
3764    pass
class Quantile(AggFunc):
3767class Quantile(AggFunc):
3768    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3773class Quantiles(AggFunc):
3774    arg_types = {"parameters": True, "expressions": True}
3775    is_var_len_args = True
class QuantileIf(AggFunc):
3778class QuantileIf(AggFunc):
3779    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3782class ApproxQuantile(Quantile):
3783    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3786class RangeN(Func):
3787    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3790class ReadCSV(Func):
3791    _sql_names = ["READ_CSV"]
3792    is_var_len_args = True
3793    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3796class Reduce(Func):
3797    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3800class RegexpExtract(Func):
3801    arg_types = {
3802        "this": True,
3803        "expression": True,
3804        "position": False,
3805        "occurrence": False,
3806        "group": False,
3807    }
class RegexpLike(Func):
3810class RegexpLike(Func):
3811    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3814class RegexpILike(Func):
3815    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3820class RegexpSplit(Func):
3821    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
3824class Repeat(Func):
3825    arg_types = {"this": True, "times": True}
class Round(Func):
3828class Round(Func):
3829    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3832class RowNumber(Func):
3833    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3836class SafeDivide(Func):
3837    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3840class SetAgg(AggFunc):
3841    pass
class SortArray(Func):
3844class SortArray(Func):
3845    arg_types = {"this": True, "asc": False}
class Split(Func):
3848class Split(Func):
3849    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3854class Substring(Func):
3855    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3858class StrPosition(Func):
3859    arg_types = {
3860        "this": True,
3861        "substr": True,
3862        "position": False,
3863        "instance": False,
3864    }
class StrToDate(Func):
3867class StrToDate(Func):
3868    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3871class StrToTime(Func):
3872    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3877class StrToUnix(Func):
3878    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3881class NumberToStr(Func):
3882    arg_types = {"this": True, "format": True}
class Struct(Func):
3885class Struct(Func):
3886    arg_types = {"expressions": True}
3887    is_var_len_args = True
class StructExtract(Func):
3890class StructExtract(Func):
3891    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3894class Sum(AggFunc):
3895    pass
class Sqrt(Func):
3898class Sqrt(Func):
3899    pass
class Stddev(AggFunc):
3902class Stddev(AggFunc):
3903    pass
class StddevPop(AggFunc):
3906class StddevPop(AggFunc):
3907    pass
class StddevSamp(AggFunc):
3910class StddevSamp(AggFunc):
3911    pass
class TimeToStr(Func):
3914class TimeToStr(Func):
3915    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3918class TimeToTimeStr(Func):
3919    pass
class TimeToUnix(Func):
3922class TimeToUnix(Func):
3923    pass
class TimeStrToDate(Func):
3926class TimeStrToDate(Func):
3927    pass
class TimeStrToTime(Func):
3930class TimeStrToTime(Func):
3931    pass
class TimeStrToUnix(Func):
3934class TimeStrToUnix(Func):
3935    pass
class Trim(Func):
3938class Trim(Func):
3939    arg_types = {
3940        "this": True,
3941        "expression": False,
3942        "position": False,
3943        "collation": False,
3944    }
class TsOrDsAdd(Func, TimeUnit):
3947class TsOrDsAdd(Func, TimeUnit):
3948    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3951class TsOrDsToDateStr(Func):
3952    pass
class TsOrDsToDate(Func):
3955class TsOrDsToDate(Func):
3956    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3959class TsOrDiToDi(Func):
3960    pass
class Unhex(Func):
3963class Unhex(Func):
3964    pass
class UnixToStr(Func):
3967class UnixToStr(Func):
3968    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3973class UnixToTime(Func):
3974    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3975
3976    SECONDS = Literal.string("seconds")
3977    MILLIS = Literal.string("millis")
3978    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3981class UnixToTimeStr(Func):
3982    pass
class Upper(Func):
3985class Upper(Func):
3986    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3989class Variance(AggFunc):
3990    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3993class VariancePop(AggFunc):
3994    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3997class Week(Func):
3998    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4001class XMLTable(Func):
4002    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4005class Year(Func):
4006    pass
class Use(Expression):
4009class Use(Expression):
4010    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4013class Merge(Expression):
4014    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4017class When(Func):
4018    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4029def maybe_parse(
4030    sql_or_expression: ExpOrStr,
4031    *,
4032    into: t.Optional[IntoType] = None,
4033    dialect: DialectType = None,
4034    prefix: t.Optional[str] = None,
4035    copy: bool = False,
4036    **opts,
4037) -> Expression:
4038    """Gracefully handle a possible string or expression.
4039
4040    Example:
4041        >>> maybe_parse("1")
4042        (LITERAL this: 1, is_string: False)
4043        >>> maybe_parse(to_identifier("x"))
4044        (IDENTIFIER this: x, quoted: False)
4045
4046    Args:
4047        sql_or_expression: the SQL code string or an expression
4048        into: the SQLGlot Expression to parse into
4049        dialect: the dialect used to parse the input expressions (in the case that an
4050            input expression is a SQL string).
4051        prefix: a string to prefix the sql with before it gets parsed
4052            (automatically includes a space)
4053        copy: whether or not to copy the expression.
4054        **opts: other options to use to parse the input expressions (again, in the case
4055            that an input expression is a SQL string).
4056
4057    Returns:
4058        Expression: the parsed or given expression.
4059    """
4060    if isinstance(sql_or_expression, Expression):
4061        if copy:
4062            return sql_or_expression.copy()
4063        return sql_or_expression
4064
4065    import sqlglot
4066
4067    sql = str(sql_or_expression)
4068    if prefix:
4069        sql = f"{prefix} {sql}"
4070    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4216def union(left, right, distinct=True, dialect=None, **opts):
4217    """
4218    Initializes a syntax tree from one UNION expression.
4219
4220    Example:
4221        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4222        'SELECT * FROM foo UNION SELECT * FROM bla'
4223
4224    Args:
4225        left (str | Expression): the SQL code string corresponding to the left-hand side.
4226            If an `Expression` instance is passed, it will be used as-is.
4227        right (str | Expression): the SQL code string corresponding to the right-hand side.
4228            If an `Expression` instance is passed, it will be used as-is.
4229        distinct (bool): set the DISTINCT flag if and only if this is true.
4230        dialect (str): the dialect used to parse the input expression.
4231        opts (kwargs): other options to use to parse the input expressions.
4232    Returns:
4233        Union: the syntax tree for the UNION expression.
4234    """
4235    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4236    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4237
4238    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4241def intersect(left, right, distinct=True, dialect=None, **opts):
4242    """
4243    Initializes a syntax tree from one INTERSECT expression.
4244
4245    Example:
4246        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4247        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4248
4249    Args:
4250        left (str | Expression): the SQL code string corresponding to the left-hand side.
4251            If an `Expression` instance is passed, it will be used as-is.
4252        right (str | Expression): the SQL code string corresponding to the right-hand side.
4253            If an `Expression` instance is passed, it will be used as-is.
4254        distinct (bool): set the DISTINCT flag if and only if this is true.
4255        dialect (str): the dialect used to parse the input expression.
4256        opts (kwargs): other options to use to parse the input expressions.
4257    Returns:
4258        Intersect: the syntax tree for the INTERSECT expression.
4259    """
4260    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4261    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4262
4263    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4266def except_(left, right, distinct=True, dialect=None, **opts):
4267    """
4268    Initializes a syntax tree from one EXCEPT expression.
4269
4270    Example:
4271        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4272        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4273
4274    Args:
4275        left (str | Expression): the SQL code string corresponding to the left-hand side.
4276            If an `Expression` instance is passed, it will be used as-is.
4277        right (str | Expression): the SQL code string corresponding to the right-hand side.
4278            If an `Expression` instance is passed, it will be used as-is.
4279        distinct (bool): set the DISTINCT flag if and only if this is true.
4280        dialect (str): the dialect used to parse the input expression.
4281        opts (kwargs): other options to use to parse the input expressions.
4282    Returns:
4283        Except: the syntax tree for the EXCEPT statement.
4284    """
4285    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4286    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4287
4288    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4291def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4292    """
4293    Initializes a syntax tree from one or multiple SELECT expressions.
4294
4295    Example:
4296        >>> select("col1", "col2").from_("tbl").sql()
4297        'SELECT col1, col2 FROM tbl'
4298
4299    Args:
4300        *expressions: the SQL code string to parse as the expressions of a
4301            SELECT statement. If an Expression instance is passed, this is used as-is.
4302        dialect: the dialect used to parse the input expressions (in the case that an
4303            input expression is a SQL string).
4304        **opts: other options to use to parse the input expressions (again, in the case
4305            that an input expression is a SQL string).
4306
4307    Returns:
4308        Select: the syntax tree for the SELECT statement.
4309    """
4310    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4313def from_(*expressions, dialect=None, **opts) -> Select:
4314    """
4315    Initializes a syntax tree from a FROM expression.
4316
4317    Example:
4318        >>> from_("tbl").select("col1", "col2").sql()
4319        'SELECT col1, col2 FROM tbl'
4320
4321    Args:
4322        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4323            SELECT statement. If an Expression instance is passed, this is used as-is.
4324        dialect (str): the dialect used to parse the input expression (in the case that the
4325            input expression is a SQL string).
4326        **opts: other options to use to parse the input expressions (again, in the case
4327            that the input expression is a SQL string).
4328
4329    Returns:
4330        Select: the syntax tree for the SELECT statement.
4331    """
4332    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4335def update(
4336    table: str | Table,
4337    properties: dict,
4338    where: t.Optional[ExpOrStr] = None,
4339    from_: t.Optional[ExpOrStr] = None,
4340    dialect: DialectType = None,
4341    **opts,
4342) -> Update:
4343    """
4344    Creates an update statement.
4345
4346    Example:
4347        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4348        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4349
4350    Args:
4351        *properties: dictionary of properties to set which are
4352            auto converted to sql objects eg None -> NULL
4353        where: sql conditional parsed into a WHERE statement
4354        from_: sql statement parsed into a FROM statement
4355        dialect: the dialect used to parse the input expressions.
4356        **opts: other options to use to parse the input expressions.
4357
4358    Returns:
4359        Update: the syntax tree for the UPDATE statement.
4360    """
4361    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4362    update_expr.set(
4363        "expressions",
4364        [
4365            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4366            for k, v in properties.items()
4367        ],
4368    )
4369    if from_:
4370        update_expr.set(
4371            "from",
4372            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4373        )
4374    if isinstance(where, Condition):
4375        where = Where(this=where)
4376    if where:
4377        update_expr.set(
4378            "where",
4379            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4380        )
4381    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4384def delete(
4385    table: ExpOrStr,
4386    where: t.Optional[ExpOrStr] = None,
4387    returning: t.Optional[ExpOrStr] = None,
4388    dialect: DialectType = None,
4389    **opts,
4390) -> Delete:
4391    """
4392    Builds a delete statement.
4393
4394    Example:
4395        >>> delete("my_table", where="id > 1").sql()
4396        'DELETE FROM my_table WHERE id > 1'
4397
4398    Args:
4399        where: sql conditional parsed into a WHERE statement
4400        returning: sql conditional parsed into a RETURNING statement
4401        dialect: the dialect used to parse the input expressions.
4402        **opts: other options to use to parse the input expressions.
4403
4404    Returns:
4405        Delete: the syntax tree for the DELETE statement.
4406    """
4407    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4408    if where:
4409        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4410    if returning:
4411        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4412    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4415def condition(expression, dialect=None, **opts) -> Condition:
4416    """
4417    Initialize a logical condition expression.
4418
4419    Example:
4420        >>> condition("x=1").sql()
4421        'x = 1'
4422
4423        This is helpful for composing larger logical syntax trees:
4424        >>> where = condition("x=1")
4425        >>> where = where.and_("y=1")
4426        >>> Select().from_("tbl").select("*").where(where).sql()
4427        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4428
4429    Args:
4430        *expression (str | Expression): the SQL code string to parse.
4431            If an Expression instance is passed, this is used as-is.
4432        dialect (str): the dialect used to parse the input expression (in the case that the
4433            input expression is a SQL string).
4434        **opts: other options to use to parse the input expressions (again, in the case
4435            that the input expression is a SQL string).
4436
4437    Returns:
4438        Condition: the expression
4439    """
4440    return maybe_parse(  # type: ignore
4441        expression,
4442        into=Condition,
4443        dialect=dialect,
4444        **opts,
4445    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4448def and_(*expressions, dialect=None, **opts) -> And:
4449    """
4450    Combine multiple conditions with an AND logical operator.
4451
4452    Example:
4453        >>> and_("x=1", and_("y=1", "z=1")).sql()
4454        'x = 1 AND (y = 1 AND z = 1)'
4455
4456    Args:
4457        *expressions (str | Expression): the SQL code strings to parse.
4458            If an Expression instance is passed, this is used as-is.
4459        dialect (str): the dialect used to parse the input expression.
4460        **opts: other options to use to parse the input expressions.
4461
4462    Returns:
4463        And: the new condition
4464    """
4465    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4468def or_(*expressions, dialect=None, **opts) -> Or:
4469    """
4470    Combine multiple conditions with an OR logical operator.
4471
4472    Example:
4473        >>> or_("x=1", or_("y=1", "z=1")).sql()
4474        'x = 1 OR (y = 1 OR z = 1)'
4475
4476    Args:
4477        *expressions (str | Expression): the SQL code strings to parse.
4478            If an Expression instance is passed, this is used as-is.
4479        dialect (str): the dialect used to parse the input expression.
4480        **opts: other options to use to parse the input expressions.
4481
4482    Returns:
4483        Or: the new condition
4484    """
4485    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4488def not_(expression, dialect=None, **opts) -> Not:
4489    """
4490    Wrap a condition with a NOT operator.
4491
4492    Example:
4493        >>> not_("this_suit='black'").sql()
4494        "NOT this_suit = 'black'"
4495
4496    Args:
4497        expression (str | Expression): the SQL code strings to parse.
4498            If an Expression instance is passed, this is used as-is.
4499        dialect (str): the dialect used to parse the input expression.
4500        **opts: other options to use to parse the input expressions.
4501
4502    Returns:
4503        Not: the new condition
4504    """
4505    this = condition(
4506        expression,
4507        dialect=dialect,
4508        **opts,
4509    )
4510    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4513def paren(expression) -> Paren:
4514    return Paren(this=expression)
def to_identifier(name, quoted=None):
4530def to_identifier(name, quoted=None):
4531    """Builds an identifier.
4532
4533    Args:
4534        name: The name to turn into an identifier.
4535        quoted: Whether or not force quote the identifier.
4536
4537    Returns:
4538        The identifier ast node.
4539    """
4540
4541    if name is None:
4542        return None
4543
4544    if isinstance(name, Identifier):
4545        identifier = name
4546    elif isinstance(name, str):
4547        identifier = Identifier(
4548            this=name,
4549            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4550        )
4551    else:
4552        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4553    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4559def to_interval(interval: str | Literal) -> Interval:
4560    """Builds an interval expression from a string like '1 day' or '5 months'."""
4561    if isinstance(interval, Literal):
4562        if not interval.is_string:
4563            raise ValueError("Invalid interval string.")
4564
4565        interval = interval.this
4566
4567    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4568
4569    if not interval_parts:
4570        raise ValueError("Invalid interval string.")
4571
4572    return Interval(
4573        this=Literal.string(interval_parts.group(1)),
4574        unit=Var(this=interval_parts.group(2)),
4575    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4588def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4589    """
4590    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4591    If a table is passed in then that table is returned.
4592
4593    Args:
4594        sql_path: a `[catalog].[schema].[table]` string.
4595
4596    Returns:
4597        A table expression.
4598    """
4599    if sql_path is None or isinstance(sql_path, Table):
4600        return sql_path
4601    if not isinstance(sql_path, str):
4602        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4603
4604    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4605    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4608def to_column(sql_path: str | Column, **kwargs) -> Column:
4609    """
4610    Create a column from a `[table].[column]` sql path. Schema is optional.
4611
4612    If a column is passed in then that column is returned.
4613
4614    Args:
4615        sql_path: `[table].[column]` string
4616    Returns:
4617        Table: A column expression
4618    """
4619    if sql_path is None or isinstance(sql_path, Column):
4620        return sql_path
4621    if not isinstance(sql_path, str):
4622        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4623    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4626def alias_(
4627    expression: ExpOrStr,
4628    alias: str | Identifier,
4629    table: bool | t.Sequence[str | Identifier] = False,
4630    quoted: t.Optional[bool] = None,
4631    dialect: DialectType = None,
4632    **opts,
4633):
4634    """Create an Alias expression.
4635
4636    Example:
4637        >>> alias_('foo', 'bar').sql()
4638        'foo AS bar'
4639
4640        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4641        '(SELECT 1, 2) AS bar(a, b)'
4642
4643    Args:
4644        expression: the SQL code strings to parse.
4645            If an Expression instance is passed, this is used as-is.
4646        alias: the alias name to use. If the name has
4647            special characters it is quoted.
4648        table: Whether or not to create a table alias, can also be a list of columns.
4649        quoted: whether or not to quote the alias
4650        dialect: the dialect used to parse the input expression.
4651        **opts: other options to use to parse the input expressions.
4652
4653    Returns:
4654        Alias: the aliased expression
4655    """
4656    exp = maybe_parse(expression, dialect=dialect, **opts)
4657    alias = to_identifier(alias, quoted=quoted)
4658
4659    if table:
4660        table_alias = TableAlias(this=alias)
4661        exp.set("alias", table_alias)
4662
4663        if not isinstance(table, bool):
4664            for column in table:
4665                table_alias.append("columns", to_identifier(column, quoted=quoted))
4666
4667        return exp
4668
4669    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4670    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4671    # for the complete Window expression.
4672    #
4673    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4674
4675    if "alias" in exp.arg_types and not isinstance(exp, Window):
4676        exp = exp.copy()
4677        exp.set("alias", alias)
4678        return exp
4679    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4682def subquery(expression, alias=None, dialect=None, **opts):
4683    """
4684    Build a subquery expression.
4685
4686    Example:
4687        >>> subquery('select x from tbl', 'bar').select('x').sql()
4688        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4689
4690    Args:
4691        expression (str | Expression): the SQL code strings to parse.
4692            If an Expression instance is passed, this is used as-is.
4693        alias (str | Expression): the alias name to use.
4694        dialect (str): the dialect used to parse the input expression.
4695        **opts: other options to use to parse the input expressions.
4696
4697    Returns:
4698        Select: a new select with the subquery expression included
4699    """
4700
4701    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4702    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4705def column(
4706    col: str | Identifier,
4707    table: t.Optional[str | Identifier] = None,
4708    db: t.Optional[str | Identifier] = None,
4709    catalog: t.Optional[str | Identifier] = None,
4710    quoted: t.Optional[bool] = None,
4711) -> Column:
4712    """
4713    Build a Column.
4714
4715    Args:
4716        col: column name
4717        table: table name
4718        db: db name
4719        catalog: catalog name
4720        quoted: whether or not to force quote each part
4721    Returns:
4722        Column: column instance
4723    """
4724    return Column(
4725        this=to_identifier(col, quoted=quoted),
4726        table=to_identifier(table, quoted=quoted),
4727        db=to_identifier(db, quoted=quoted),
4728        catalog=to_identifier(catalog, quoted=quoted),
4729    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4732def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4733    """Cast an expression to a data type.
4734
4735    Example:
4736        >>> cast('x + 1', 'int').sql()
4737        'CAST(x + 1 AS INT)'
4738
4739    Args:
4740        expression: The expression to cast.
4741        to: The datatype to cast to.
4742
4743    Returns:
4744        A cast node.
4745    """
4746    expression = maybe_parse(expression, **opts)
4747    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4750def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4751    """Build a Table.
4752
4753    Args:
4754        table (str | Expression): column name
4755        db (str | Expression): db name
4756        catalog (str | Expression): catalog name
4757
4758    Returns:
4759        Table: table instance
4760    """
4761    return Table(
4762        this=to_identifier(table, quoted=quoted),
4763        db=to_identifier(db, quoted=quoted),
4764        catalog=to_identifier(catalog, quoted=quoted),
4765        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4766    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4769def values(
4770    values: t.Iterable[t.Tuple[t.Any, ...]],
4771    alias: t.Optional[str] = None,
4772    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4773) -> Values:
4774    """Build VALUES statement.
4775
4776    Example:
4777        >>> values([(1, '2')]).sql()
4778        "VALUES (1, '2')"
4779
4780    Args:
4781        values: values statements that will be converted to SQL
4782        alias: optional alias
4783        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4784         If either are provided then an alias is also required.
4785         If a dictionary is provided then the first column of the values will be casted to the expected type
4786         in order to help with type inference.
4787
4788    Returns:
4789        Values: the Values expression object
4790    """
4791    if columns and not alias:
4792        raise ValueError("Alias is required when providing columns")
4793    table_alias = (
4794        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4795        if columns
4796        else TableAlias(this=to_identifier(alias) if alias else None)
4797    )
4798    expressions = [convert(tup) for tup in values]
4799    if columns and isinstance(columns, dict):
4800        types = list(columns.values())
4801        expressions[0].set(
4802            "expressions",
4803            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4804        )
4805    return Values(
4806        expressions=expressions,
4807        alias=table_alias,
4808    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4811def var(name: t.Optional[ExpOrStr]) -> Var:
4812    """Build a SQL variable.
4813
4814    Example:
4815        >>> repr(var('x'))
4816        '(VAR this: x)'
4817
4818        >>> repr(var(column('x', table='y')))
4819        '(VAR this: x)'
4820
4821    Args:
4822        name: The name of the var or an expression who's name will become the var.
4823
4824    Returns:
4825        The new variable node.
4826    """
4827    if not name:
4828        raise ValueError("Cannot convert empty name into var.")
4829
4830    if isinstance(name, Expression):
4831        name = name.name
4832    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4835def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4836    """Build ALTER TABLE... RENAME... expression
4837
4838    Args:
4839        old_name: The old name of the table
4840        new_name: The new name of the table
4841
4842    Returns:
4843        Alter table expression
4844    """
4845    old_table = to_table(old_name)
4846    new_table = to_table(new_name)
4847    return AlterTable(
4848        this=old_table,
4849        actions=[
4850            RenameTable(this=new_table),
4851        ],
4852    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4855def convert(value) -> Expression:
4856    """Convert a python value into an expression object.
4857
4858    Raises an error if a conversion is not possible.
4859
4860    Args:
4861        value (Any): a python object
4862
4863    Returns:
4864        Expression: the equivalent expression object
4865    """
4866    if isinstance(value, Expression):
4867        return value
4868    if value is None:
4869        return NULL
4870    if isinstance(value, bool):
4871        return Boolean(this=value)
4872    if isinstance(value, str):
4873        return Literal.string(value)
4874    if isinstance(value, float) and math.isnan(value):
4875        return NULL
4876    if isinstance(value, numbers.Number):
4877        return Literal.number(value)
4878    if isinstance(value, tuple):
4879        return Tuple(expressions=[convert(v) for v in value])
4880    if isinstance(value, list):
4881        return Array(expressions=[convert(v) for v in value])
4882    if isinstance(value, dict):
4883        return Map(
4884            keys=[convert(k) for k in value],
4885            values=[convert(v) for v in value.values()],
4886        )
4887    if isinstance(value, datetime.datetime):
4888        datetime_literal = Literal.string(
4889            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4890        )
4891        return TimeStrToTime(this=datetime_literal)
4892    if isinstance(value, datetime.date):
4893        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4894        return DateStrToDate(this=date_literal)
4895    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4898def replace_children(expression, fun, *args, **kwargs):
4899    """
4900    Replace children of an expression with the result of a lambda fun(child) -> exp.
4901    """
4902    for k, v in expression.args.items():
4903        is_list_arg = type(v) is list
4904
4905        child_nodes = v if is_list_arg else [v]
4906        new_child_nodes = []
4907
4908        for cn in child_nodes:
4909            if isinstance(cn, Expression):
4910                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4911                    new_child_nodes.append(child_node)
4912                    child_node.parent = expression
4913                    child_node.arg_key = k
4914            else:
4915                new_child_nodes.append(cn)
4916
4917        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4920def column_table_names(expression):
4921    """
4922    Return all table names referenced through columns in an expression.
4923
4924    Example:
4925        >>> import sqlglot
4926        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4927        ['c', 'a']
4928
4929    Args:
4930        expression (sqlglot.Expression): expression to find table names
4931
4932    Returns:
4933        list: A list of unique names
4934    """
4935    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4938def table_name(table) -> str:
4939    """Get the full name of a table as a string.
4940
4941    Args:
4942        table (exp.Table | str): table expression node or string.
4943
4944    Examples:
4945        >>> from sqlglot import exp, parse_one
4946        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4947        'a.b.c'
4948
4949    Returns:
4950        The table name.
4951    """
4952
4953    table = maybe_parse(table, into=Table)
4954
4955    if not table:
4956        raise ValueError(f"Cannot parse {table}")
4957
4958    return ".".join(
4959        part
4960        for part in (
4961            table.text("catalog"),
4962            table.text("db"),
4963            table.name,
4964        )
4965        if part
4966    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
4969def replace_tables(expression, mapping):
4970    """Replace all tables in expression according to the mapping.
4971
4972    Args:
4973        expression (sqlglot.Expression): expression node to be transformed and replaced.
4974        mapping (Dict[str, str]): mapping of table names.
4975
4976    Examples:
4977        >>> from sqlglot import exp, parse_one
4978        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4979        'SELECT * FROM c'
4980
4981    Returns:
4982        The mapped expression.
4983    """
4984
4985    def _replace_tables(node):
4986        if isinstance(node, Table):
4987            new_name = mapping.get(table_name(node))
4988            if new_name:
4989                return to_table(
4990                    new_name,
4991                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4992                )
4993        return node
4994
4995    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
4998def replace_placeholders(expression, *args, **kwargs):
4999    """Replace placeholders in an expression.
5000
5001    Args:
5002        expression (sqlglot.Expression): expression node to be transformed and replaced.
5003        args: positional names that will substitute unnamed placeholders in the given order.
5004        kwargs: keyword arguments that will substitute named placeholders.
5005
5006    Examples:
5007        >>> from sqlglot import exp, parse_one
5008        >>> replace_placeholders(
5009        ...     parse_one("select * from :tbl where ? = ?"),
5010        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5011        ... ).sql()
5012        "SELECT * FROM foo WHERE str_col = 'b'"
5013
5014    Returns:
5015        The mapped expression.
5016    """
5017
5018    def _replace_placeholders(node, args, **kwargs):
5019        if isinstance(node, Placeholder):
5020            if node.name:
5021                new_name = kwargs.get(node.name)
5022                if new_name:
5023                    return convert(new_name)
5024            else:
5025                try:
5026                    return convert(next(args))
5027                except StopIteration:
5028                    pass
5029        return node
5030
5031    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
5034def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5035    """Transforms an expression by expanding all referenced sources into subqueries.
5036
5037    Examples:
5038        >>> from sqlglot import parse_one
5039        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5040        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5041
5042    Args:
5043        expression: The expression to expand.
5044        sources: A dictionary of name to Subqueryables.
5045        copy: Whether or not to copy the expression during transformation. Defaults to True.
5046
5047    Returns:
5048        The transformed expression.
5049    """
5050
5051    def _expand(node: Expression):
5052        if isinstance(node, Table):
5053            name = table_name(node)
5054            source = sources.get(name)
5055            if source:
5056                subquery = source.subquery(node.alias or name)
5057                subquery.comments = [f"source: {name}"]
5058                return subquery
5059        return node
5060
5061    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5064def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5065    """
5066    Returns a Func expression.
5067
5068    Examples:
5069        >>> func("abs", 5).sql()
5070        'ABS(5)'
5071
5072        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5073        'CAST(5 AS DOUBLE)'
5074
5075    Args:
5076        name: the name of the function to build.
5077        args: the args used to instantiate the function of interest.
5078        dialect: the source dialect.
5079        kwargs: the kwargs used to instantiate the function of interest.
5080
5081    Note:
5082        The arguments `args` and `kwargs` are mutually exclusive.
5083
5084    Returns:
5085        An instance of the function of interest, or an anonymous function, if `name` doesn't
5086        correspond to an existing `sqlglot.expressions.Func` class.
5087    """
5088    if args and kwargs:
5089        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5090
5091    from sqlglot.dialects.dialect import Dialect
5092
5093    converted = [convert(arg) for arg in args]
5094    kwargs = {key: convert(value) for key, value in kwargs.items()}
5095
5096    parser = Dialect.get_or_raise(dialect)().parser()
5097    from_args_list = parser.FUNCTIONS.get(name.upper())
5098
5099    if from_args_list:
5100        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5101    else:
5102        kwargs = kwargs or {"expressions": converted}
5103        function = Anonymous(this=name, **kwargs)
5104
5105    for error_message in function.error_messages(converted):
5106        raise ValueError(error_message)
5107
5108    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5111def true():
5112    """
5113    Returns a true Boolean expression.
5114    """
5115    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5118def false():
5119    """
5120    Returns a false Boolean expression.
5121    """
5122    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5125def null():
5126    """
5127    Returns a Null expression.
5128    """
5129    return Null()

Returns a Null expression.